Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Maintain the same structure and functionality when rewriting this code in C#. | (use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items)))
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Transform the following Clojure implementation into C++, maintaining the same output and logic. | (use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items)))
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Please provide an equivalent version of this Clojure code in Java. | (use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items)))
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Port the following code from Clojure to Python with equivalent syntax and logic. | (use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items)))
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Translate the given Clojure code snippet into VB without altering its behavior. | (use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items)))
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Rewrite the snippet below in Go so it works the same as the original Clojure code. | (use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items)))
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Rewrite this program in C while keeping its functionality equivalent to the Common_Lisp version. | (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.
Test is used to compare elements, and should be a suitable test for
hash-tables. Topological-sort returns two values. The first is a
list of objects sorted toplogically. The second is a boolean
indicating whether all of the objects in the input graph are present
in the topological ordering (i.e., the first value)."
(let ((entries (make-hash-table :test test)))
(flet ((entry (vertex)
"Return the entry for vertex. Each entry is a cons whose
car is the number of outstanding dependencies of vertex
and whose cdr is a list of dependants of vertex."
(multiple-value-bind (entry presentp) (gethash vertex entries)
(if presentp entry
(setf (gethash vertex entries) (cons 0 '()))))))
(dolist (vertex graph)
(destructuring-bind (vertex &rest dependencies) vertex
(let ((ventry (entry vertex)))
(dolist (dependency dependencies)
(let ((dentry (entry dependency)))
(unless (funcall test dependency vertex)
(incf (car ventry))
(push vertex (cdr dentry))))))))
(let ((L '())
(S (loop for entry being each hash-value of entries
using (hash-key vertex)
when (zerop (car entry)) collect vertex)))
(do* () ((endp S))
(let* ((v (pop S)) (ventry (entry v)))
(remhash v entries)
(dolist (dependant (cdr ventry) (push v L))
(when (zerop (decf (car (entry dependant))))
(push dependant S)))))
(let ((all-sorted-p (zerop (hash-table-count entries))))
(values (nreverse L)
all-sorted-p
(unless all-sorted-p
entries)))))))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Convert the following code from Common_Lisp to C#, ensuring the logic remains intact. | (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.
Test is used to compare elements, and should be a suitable test for
hash-tables. Topological-sort returns two values. The first is a
list of objects sorted toplogically. The second is a boolean
indicating whether all of the objects in the input graph are present
in the topological ordering (i.e., the first value)."
(let ((entries (make-hash-table :test test)))
(flet ((entry (vertex)
"Return the entry for vertex. Each entry is a cons whose
car is the number of outstanding dependencies of vertex
and whose cdr is a list of dependants of vertex."
(multiple-value-bind (entry presentp) (gethash vertex entries)
(if presentp entry
(setf (gethash vertex entries) (cons 0 '()))))))
(dolist (vertex graph)
(destructuring-bind (vertex &rest dependencies) vertex
(let ((ventry (entry vertex)))
(dolist (dependency dependencies)
(let ((dentry (entry dependency)))
(unless (funcall test dependency vertex)
(incf (car ventry))
(push vertex (cdr dentry))))))))
(let ((L '())
(S (loop for entry being each hash-value of entries
using (hash-key vertex)
when (zerop (car entry)) collect vertex)))
(do* () ((endp S))
(let* ((v (pop S)) (ventry (entry v)))
(remhash v entries)
(dolist (dependant (cdr ventry) (push v L))
(when (zerop (decf (car (entry dependant))))
(push dependant S)))))
(let ((all-sorted-p (zerop (hash-table-count entries))))
(values (nreverse L)
all-sorted-p
(unless all-sorted-p
entries)))))))
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Ensure the translated C++ code behaves exactly like the original Common_Lisp snippet. | (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.
Test is used to compare elements, and should be a suitable test for
hash-tables. Topological-sort returns two values. The first is a
list of objects sorted toplogically. The second is a boolean
indicating whether all of the objects in the input graph are present
in the topological ordering (i.e., the first value)."
(let ((entries (make-hash-table :test test)))
(flet ((entry (vertex)
"Return the entry for vertex. Each entry is a cons whose
car is the number of outstanding dependencies of vertex
and whose cdr is a list of dependants of vertex."
(multiple-value-bind (entry presentp) (gethash vertex entries)
(if presentp entry
(setf (gethash vertex entries) (cons 0 '()))))))
(dolist (vertex graph)
(destructuring-bind (vertex &rest dependencies) vertex
(let ((ventry (entry vertex)))
(dolist (dependency dependencies)
(let ((dentry (entry dependency)))
(unless (funcall test dependency vertex)
(incf (car ventry))
(push vertex (cdr dentry))))))))
(let ((L '())
(S (loop for entry being each hash-value of entries
using (hash-key vertex)
when (zerop (car entry)) collect vertex)))
(do* () ((endp S))
(let* ((v (pop S)) (ventry (entry v)))
(remhash v entries)
(dolist (dependant (cdr ventry) (push v L))
(when (zerop (decf (car (entry dependant))))
(push dependant S)))))
(let ((all-sorted-p (zerop (hash-table-count entries))))
(values (nreverse L)
all-sorted-p
(unless all-sorted-p
entries)))))))
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Keep all operations the same but rewrite the snippet in Java. | (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.
Test is used to compare elements, and should be a suitable test for
hash-tables. Topological-sort returns two values. The first is a
list of objects sorted toplogically. The second is a boolean
indicating whether all of the objects in the input graph are present
in the topological ordering (i.e., the first value)."
(let ((entries (make-hash-table :test test)))
(flet ((entry (vertex)
"Return the entry for vertex. Each entry is a cons whose
car is the number of outstanding dependencies of vertex
and whose cdr is a list of dependants of vertex."
(multiple-value-bind (entry presentp) (gethash vertex entries)
(if presentp entry
(setf (gethash vertex entries) (cons 0 '()))))))
(dolist (vertex graph)
(destructuring-bind (vertex &rest dependencies) vertex
(let ((ventry (entry vertex)))
(dolist (dependency dependencies)
(let ((dentry (entry dependency)))
(unless (funcall test dependency vertex)
(incf (car ventry))
(push vertex (cdr dentry))))))))
(let ((L '())
(S (loop for entry being each hash-value of entries
using (hash-key vertex)
when (zerop (car entry)) collect vertex)))
(do* () ((endp S))
(let* ((v (pop S)) (ventry (entry v)))
(remhash v entries)
(dolist (dependant (cdr ventry) (push v L))
(when (zerop (decf (car (entry dependant))))
(push dependant S)))))
(let ((all-sorted-p (zerop (hash-table-count entries))))
(values (nreverse L)
all-sorted-p
(unless all-sorted-p
entries)))))))
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Transform the following Common_Lisp implementation into Python, maintaining the same output and logic. | (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.
Test is used to compare elements, and should be a suitable test for
hash-tables. Topological-sort returns two values. The first is a
list of objects sorted toplogically. The second is a boolean
indicating whether all of the objects in the input graph are present
in the topological ordering (i.e., the first value)."
(let ((entries (make-hash-table :test test)))
(flet ((entry (vertex)
"Return the entry for vertex. Each entry is a cons whose
car is the number of outstanding dependencies of vertex
and whose cdr is a list of dependants of vertex."
(multiple-value-bind (entry presentp) (gethash vertex entries)
(if presentp entry
(setf (gethash vertex entries) (cons 0 '()))))))
(dolist (vertex graph)
(destructuring-bind (vertex &rest dependencies) vertex
(let ((ventry (entry vertex)))
(dolist (dependency dependencies)
(let ((dentry (entry dependency)))
(unless (funcall test dependency vertex)
(incf (car ventry))
(push vertex (cdr dentry))))))))
(let ((L '())
(S (loop for entry being each hash-value of entries
using (hash-key vertex)
when (zerop (car entry)) collect vertex)))
(do* () ((endp S))
(let* ((v (pop S)) (ventry (entry v)))
(remhash v entries)
(dolist (dependant (cdr ventry) (push v L))
(when (zerop (decf (car (entry dependant))))
(push dependant S)))))
(let ((all-sorted-p (zerop (hash-table-count entries))))
(values (nreverse L)
all-sorted-p
(unless all-sorted-p
entries)))))))
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Change the following Common_Lisp code into VB without altering its purpose. | (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.
Test is used to compare elements, and should be a suitable test for
hash-tables. Topological-sort returns two values. The first is a
list of objects sorted toplogically. The second is a boolean
indicating whether all of the objects in the input graph are present
in the topological ordering (i.e., the first value)."
(let ((entries (make-hash-table :test test)))
(flet ((entry (vertex)
"Return the entry for vertex. Each entry is a cons whose
car is the number of outstanding dependencies of vertex
and whose cdr is a list of dependants of vertex."
(multiple-value-bind (entry presentp) (gethash vertex entries)
(if presentp entry
(setf (gethash vertex entries) (cons 0 '()))))))
(dolist (vertex graph)
(destructuring-bind (vertex &rest dependencies) vertex
(let ((ventry (entry vertex)))
(dolist (dependency dependencies)
(let ((dentry (entry dependency)))
(unless (funcall test dependency vertex)
(incf (car ventry))
(push vertex (cdr dentry))))))))
(let ((L '())
(S (loop for entry being each hash-value of entries
using (hash-key vertex)
when (zerop (car entry)) collect vertex)))
(do* () ((endp S))
(let* ((v (pop S)) (ventry (entry v)))
(remhash v entries)
(dolist (dependant (cdr ventry) (push v L))
(when (zerop (decf (car (entry dependant))))
(push dependant S)))))
(let ((all-sorted-p (zerop (hash-table-count entries))))
(values (nreverse L)
all-sorted-p
(unless all-sorted-p
entries)))))))
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Translate the given Common_Lisp code snippet into Go without altering its behavior. | (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.
Test is used to compare elements, and should be a suitable test for
hash-tables. Topological-sort returns two values. The first is a
list of objects sorted toplogically. The second is a boolean
indicating whether all of the objects in the input graph are present
in the topological ordering (i.e., the first value)."
(let ((entries (make-hash-table :test test)))
(flet ((entry (vertex)
"Return the entry for vertex. Each entry is a cons whose
car is the number of outstanding dependencies of vertex
and whose cdr is a list of dependants of vertex."
(multiple-value-bind (entry presentp) (gethash vertex entries)
(if presentp entry
(setf (gethash vertex entries) (cons 0 '()))))))
(dolist (vertex graph)
(destructuring-bind (vertex &rest dependencies) vertex
(let ((ventry (entry vertex)))
(dolist (dependency dependencies)
(let ((dentry (entry dependency)))
(unless (funcall test dependency vertex)
(incf (car ventry))
(push vertex (cdr dentry))))))))
(let ((L '())
(S (loop for entry being each hash-value of entries
using (hash-key vertex)
when (zerop (car entry)) collect vertex)))
(do* () ((endp S))
(let* ((v (pop S)) (ventry (entry v)))
(remhash v entries)
(dolist (dependant (cdr ventry) (push v L))
(when (zerop (decf (car (entry dependant))))
(push dependant S)))))
(let ((all-sorted-p (zerop (hash-table-count entries))))
(values (nreverse L)
all-sorted-p
(unless all-sorted-p
entries)))))))
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Transform the following D implementation into C, maintaining the same output and logic. | import std.stdio, std.string, std.algorithm, std.range;
final class ArgumentException : Exception {
this(string text) pure nothrow @safe {
super(text);
}
}
alias TDependencies = string[][string];
string[][] topoSort(TDependencies d) pure {
foreach (immutable k, v; d)
d[k] = v.sort().uniq.filter!(s => s != k).array;
foreach (immutable s; d.byValue.join.sort().uniq)
if (s !in d)
d[s] = [];
string[][] sorted;
while (true) {
string[] ordered;
foreach (immutable item, const dep; d)
if (dep.empty)
ordered ~= item;
if (!ordered.empty)
sorted ~= ordered.sort().release;
else
break;
TDependencies dd;
foreach (immutable item, const dep; d)
if (!ordered.canFind(item))
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
d = dd;
}
if (d.length > 0)
throw new ArgumentException(format(
"A cyclic dependency exists amongst:\n%s", d));
return sorted;
}
void main() {
immutable data =
"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";
TDependencies deps;
foreach (immutable line; data.splitLines)
deps[line.split[0]] = line.split[1 .. $];
auto depw = deps.dup;
foreach (immutable idx, const subOrder; depw.topoSort)
writefln("#%d : %s", idx + 1, subOrder);
writeln;
depw = deps.dup;
depw["dw01"] ~= "dw04";
foreach (const subOrder; depw.topoSort)
subOrder.writeln;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Generate an equivalent C# version of this D code. | import std.stdio, std.string, std.algorithm, std.range;
final class ArgumentException : Exception {
this(string text) pure nothrow @safe {
super(text);
}
}
alias TDependencies = string[][string];
string[][] topoSort(TDependencies d) pure {
foreach (immutable k, v; d)
d[k] = v.sort().uniq.filter!(s => s != k).array;
foreach (immutable s; d.byValue.join.sort().uniq)
if (s !in d)
d[s] = [];
string[][] sorted;
while (true) {
string[] ordered;
foreach (immutable item, const dep; d)
if (dep.empty)
ordered ~= item;
if (!ordered.empty)
sorted ~= ordered.sort().release;
else
break;
TDependencies dd;
foreach (immutable item, const dep; d)
if (!ordered.canFind(item))
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
d = dd;
}
if (d.length > 0)
throw new ArgumentException(format(
"A cyclic dependency exists amongst:\n%s", d));
return sorted;
}
void main() {
immutable data =
"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";
TDependencies deps;
foreach (immutable line; data.splitLines)
deps[line.split[0]] = line.split[1 .. $];
auto depw = deps.dup;
foreach (immutable idx, const subOrder; depw.topoSort)
writefln("#%d : %s", idx + 1, subOrder);
writeln;
depw = deps.dup;
depw["dw01"] ~= "dw04";
foreach (const subOrder; depw.topoSort)
subOrder.writeln;
}
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Produce a language-to-language conversion: from D to C++, same semantics. | import std.stdio, std.string, std.algorithm, std.range;
final class ArgumentException : Exception {
this(string text) pure nothrow @safe {
super(text);
}
}
alias TDependencies = string[][string];
string[][] topoSort(TDependencies d) pure {
foreach (immutable k, v; d)
d[k] = v.sort().uniq.filter!(s => s != k).array;
foreach (immutable s; d.byValue.join.sort().uniq)
if (s !in d)
d[s] = [];
string[][] sorted;
while (true) {
string[] ordered;
foreach (immutable item, const dep; d)
if (dep.empty)
ordered ~= item;
if (!ordered.empty)
sorted ~= ordered.sort().release;
else
break;
TDependencies dd;
foreach (immutable item, const dep; d)
if (!ordered.canFind(item))
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
d = dd;
}
if (d.length > 0)
throw new ArgumentException(format(
"A cyclic dependency exists amongst:\n%s", d));
return sorted;
}
void main() {
immutable data =
"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";
TDependencies deps;
foreach (immutable line; data.splitLines)
deps[line.split[0]] = line.split[1 .. $];
auto depw = deps.dup;
foreach (immutable idx, const subOrder; depw.topoSort)
writefln("#%d : %s", idx + 1, subOrder);
writeln;
depw = deps.dup;
depw["dw01"] ~= "dw04";
foreach (const subOrder; depw.topoSort)
subOrder.writeln;
}
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Convert this D block to Java, preserving its control flow and logic. | import std.stdio, std.string, std.algorithm, std.range;
final class ArgumentException : Exception {
this(string text) pure nothrow @safe {
super(text);
}
}
alias TDependencies = string[][string];
string[][] topoSort(TDependencies d) pure {
foreach (immutable k, v; d)
d[k] = v.sort().uniq.filter!(s => s != k).array;
foreach (immutable s; d.byValue.join.sort().uniq)
if (s !in d)
d[s] = [];
string[][] sorted;
while (true) {
string[] ordered;
foreach (immutable item, const dep; d)
if (dep.empty)
ordered ~= item;
if (!ordered.empty)
sorted ~= ordered.sort().release;
else
break;
TDependencies dd;
foreach (immutable item, const dep; d)
if (!ordered.canFind(item))
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
d = dd;
}
if (d.length > 0)
throw new ArgumentException(format(
"A cyclic dependency exists amongst:\n%s", d));
return sorted;
}
void main() {
immutable data =
"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";
TDependencies deps;
foreach (immutable line; data.splitLines)
deps[line.split[0]] = line.split[1 .. $];
auto depw = deps.dup;
foreach (immutable idx, const subOrder; depw.topoSort)
writefln("#%d : %s", idx + 1, subOrder);
writeln;
depw = deps.dup;
depw["dw01"] ~= "dw04";
foreach (const subOrder; depw.topoSort)
subOrder.writeln;
}
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | import std.stdio, std.string, std.algorithm, std.range;
final class ArgumentException : Exception {
this(string text) pure nothrow @safe {
super(text);
}
}
alias TDependencies = string[][string];
string[][] topoSort(TDependencies d) pure {
foreach (immutable k, v; d)
d[k] = v.sort().uniq.filter!(s => s != k).array;
foreach (immutable s; d.byValue.join.sort().uniq)
if (s !in d)
d[s] = [];
string[][] sorted;
while (true) {
string[] ordered;
foreach (immutable item, const dep; d)
if (dep.empty)
ordered ~= item;
if (!ordered.empty)
sorted ~= ordered.sort().release;
else
break;
TDependencies dd;
foreach (immutable item, const dep; d)
if (!ordered.canFind(item))
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
d = dd;
}
if (d.length > 0)
throw new ArgumentException(format(
"A cyclic dependency exists amongst:\n%s", d));
return sorted;
}
void main() {
immutable data =
"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";
TDependencies deps;
foreach (immutable line; data.splitLines)
deps[line.split[0]] = line.split[1 .. $];
auto depw = deps.dup;
foreach (immutable idx, const subOrder; depw.topoSort)
writefln("#%d : %s", idx + 1, subOrder);
writeln;
depw = deps.dup;
depw["dw01"] ~= "dw04";
foreach (const subOrder; depw.topoSort)
subOrder.writeln;
}
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Ensure the translated VB code behaves exactly like the original D snippet. | import std.stdio, std.string, std.algorithm, std.range;
final class ArgumentException : Exception {
this(string text) pure nothrow @safe {
super(text);
}
}
alias TDependencies = string[][string];
string[][] topoSort(TDependencies d) pure {
foreach (immutable k, v; d)
d[k] = v.sort().uniq.filter!(s => s != k).array;
foreach (immutable s; d.byValue.join.sort().uniq)
if (s !in d)
d[s] = [];
string[][] sorted;
while (true) {
string[] ordered;
foreach (immutable item, const dep; d)
if (dep.empty)
ordered ~= item;
if (!ordered.empty)
sorted ~= ordered.sort().release;
else
break;
TDependencies dd;
foreach (immutable item, const dep; d)
if (!ordered.canFind(item))
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
d = dd;
}
if (d.length > 0)
throw new ArgumentException(format(
"A cyclic dependency exists amongst:\n%s", d));
return sorted;
}
void main() {
immutable data =
"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";
TDependencies deps;
foreach (immutable line; data.splitLines)
deps[line.split[0]] = line.split[1 .. $];
auto depw = deps.dup;
foreach (immutable idx, const subOrder; depw.topoSort)
writefln("#%d : %s", idx + 1, subOrder);
writeln;
depw = deps.dup;
depw["dw01"] ~= "dw04";
foreach (const subOrder; depw.topoSort)
subOrder.writeln;
}
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Ensure the translated Go code behaves exactly like the original D snippet. | import std.stdio, std.string, std.algorithm, std.range;
final class ArgumentException : Exception {
this(string text) pure nothrow @safe {
super(text);
}
}
alias TDependencies = string[][string];
string[][] topoSort(TDependencies d) pure {
foreach (immutable k, v; d)
d[k] = v.sort().uniq.filter!(s => s != k).array;
foreach (immutable s; d.byValue.join.sort().uniq)
if (s !in d)
d[s] = [];
string[][] sorted;
while (true) {
string[] ordered;
foreach (immutable item, const dep; d)
if (dep.empty)
ordered ~= item;
if (!ordered.empty)
sorted ~= ordered.sort().release;
else
break;
TDependencies dd;
foreach (immutable item, const dep; d)
if (!ordered.canFind(item))
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
d = dd;
}
if (d.length > 0)
throw new ArgumentException(format(
"A cyclic dependency exists amongst:\n%s", d));
return sorted;
}
void main() {
immutable data =
"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";
TDependencies deps;
foreach (immutable line; data.splitLines)
deps[line.split[0]] = line.split[1 .. $];
auto depw = deps.dup;
foreach (immutable idx, const subOrder; depw.topoSort)
writefln("#%d : %s", idx + 1, subOrder);
writeln;
depw = deps.dup;
depw["dw01"] ~= "dw04";
foreach (const subOrder; depw.topoSort)
subOrder.writeln;
}
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Ensure the translated C code behaves exactly like the original Elixir snippet. | defmodule Topological do
def sort(library) do
g = :digraph.new
Enum.each(library, fn {l,deps} ->
:digraph.add_vertex(g,l)
Enum.each(deps, fn d -> add_dependency(g,l,d) end)
end)
if t = :digraph_utils.topsort(g) do
print_path(t)
else
IO.puts "Unsortable contains circular dependencies:"
Enum.each(:digraph.vertices(g), fn v ->
if vs = :digraph.get_short_cycle(g,v), do: print_path(vs)
end)
end
end
defp print_path(l), do: IO.puts Enum.join(l, " -> ")
defp add_dependency(_g,l,l), do: :ok
defp add_dependency(g,l,d) do
:digraph.add_vertex(g,d)
:digraph.add_edge(g,d,l)
end
end
libraries = [
des_system_lib: ~w[std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]a,
dw01: ~w[ieee dw01 dware gtech]a,
dw02: ~w[ieee dw02 dware]a,
dw03: ~w[std synopsys dware dw03 dw02 dw01 ieee gtech]a,
dw04: ~w[dw04 ieee dw01 dware gtech]a,
dw05: ~w[dw05 ieee dware]a,
dw06: ~w[dw06 ieee dware]a,
dw07: ~w[ieee dware]a,
dware: ~w[ieee dware]a,
gtech: ~w[ieee gtech]a,
ramlib: ~w[std ieee]a,
std_cell_lib: ~w[ieee std_cell_lib]a,
synopsys: []
]
Topological.sort(libraries)
IO.puts ""
bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1])
Topological.sort(bad_libraries)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Produce a language-to-language conversion: from Elixir to C#, same semantics. | defmodule Topological do
def sort(library) do
g = :digraph.new
Enum.each(library, fn {l,deps} ->
:digraph.add_vertex(g,l)
Enum.each(deps, fn d -> add_dependency(g,l,d) end)
end)
if t = :digraph_utils.topsort(g) do
print_path(t)
else
IO.puts "Unsortable contains circular dependencies:"
Enum.each(:digraph.vertices(g), fn v ->
if vs = :digraph.get_short_cycle(g,v), do: print_path(vs)
end)
end
end
defp print_path(l), do: IO.puts Enum.join(l, " -> ")
defp add_dependency(_g,l,l), do: :ok
defp add_dependency(g,l,d) do
:digraph.add_vertex(g,d)
:digraph.add_edge(g,d,l)
end
end
libraries = [
des_system_lib: ~w[std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]a,
dw01: ~w[ieee dw01 dware gtech]a,
dw02: ~w[ieee dw02 dware]a,
dw03: ~w[std synopsys dware dw03 dw02 dw01 ieee gtech]a,
dw04: ~w[dw04 ieee dw01 dware gtech]a,
dw05: ~w[dw05 ieee dware]a,
dw06: ~w[dw06 ieee dware]a,
dw07: ~w[ieee dware]a,
dware: ~w[ieee dware]a,
gtech: ~w[ieee gtech]a,
ramlib: ~w[std ieee]a,
std_cell_lib: ~w[ieee std_cell_lib]a,
synopsys: []
]
Topological.sort(libraries)
IO.puts ""
bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1])
Topological.sort(bad_libraries)
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Produce a functionally identical C++ code for the snippet given in Elixir. | defmodule Topological do
def sort(library) do
g = :digraph.new
Enum.each(library, fn {l,deps} ->
:digraph.add_vertex(g,l)
Enum.each(deps, fn d -> add_dependency(g,l,d) end)
end)
if t = :digraph_utils.topsort(g) do
print_path(t)
else
IO.puts "Unsortable contains circular dependencies:"
Enum.each(:digraph.vertices(g), fn v ->
if vs = :digraph.get_short_cycle(g,v), do: print_path(vs)
end)
end
end
defp print_path(l), do: IO.puts Enum.join(l, " -> ")
defp add_dependency(_g,l,l), do: :ok
defp add_dependency(g,l,d) do
:digraph.add_vertex(g,d)
:digraph.add_edge(g,d,l)
end
end
libraries = [
des_system_lib: ~w[std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]a,
dw01: ~w[ieee dw01 dware gtech]a,
dw02: ~w[ieee dw02 dware]a,
dw03: ~w[std synopsys dware dw03 dw02 dw01 ieee gtech]a,
dw04: ~w[dw04 ieee dw01 dware gtech]a,
dw05: ~w[dw05 ieee dware]a,
dw06: ~w[dw06 ieee dware]a,
dw07: ~w[ieee dware]a,
dware: ~w[ieee dware]a,
gtech: ~w[ieee gtech]a,
ramlib: ~w[std ieee]a,
std_cell_lib: ~w[ieee std_cell_lib]a,
synopsys: []
]
Topological.sort(libraries)
IO.puts ""
bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1])
Topological.sort(bad_libraries)
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Translate this program into Java but keep the logic exactly as in Elixir. | defmodule Topological do
def sort(library) do
g = :digraph.new
Enum.each(library, fn {l,deps} ->
:digraph.add_vertex(g,l)
Enum.each(deps, fn d -> add_dependency(g,l,d) end)
end)
if t = :digraph_utils.topsort(g) do
print_path(t)
else
IO.puts "Unsortable contains circular dependencies:"
Enum.each(:digraph.vertices(g), fn v ->
if vs = :digraph.get_short_cycle(g,v), do: print_path(vs)
end)
end
end
defp print_path(l), do: IO.puts Enum.join(l, " -> ")
defp add_dependency(_g,l,l), do: :ok
defp add_dependency(g,l,d) do
:digraph.add_vertex(g,d)
:digraph.add_edge(g,d,l)
end
end
libraries = [
des_system_lib: ~w[std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]a,
dw01: ~w[ieee dw01 dware gtech]a,
dw02: ~w[ieee dw02 dware]a,
dw03: ~w[std synopsys dware dw03 dw02 dw01 ieee gtech]a,
dw04: ~w[dw04 ieee dw01 dware gtech]a,
dw05: ~w[dw05 ieee dware]a,
dw06: ~w[dw06 ieee dware]a,
dw07: ~w[ieee dware]a,
dware: ~w[ieee dware]a,
gtech: ~w[ieee gtech]a,
ramlib: ~w[std ieee]a,
std_cell_lib: ~w[ieee std_cell_lib]a,
synopsys: []
]
Topological.sort(libraries)
IO.puts ""
bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1])
Topological.sort(bad_libraries)
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Convert the following code from Elixir to Python, ensuring the logic remains intact. | defmodule Topological do
def sort(library) do
g = :digraph.new
Enum.each(library, fn {l,deps} ->
:digraph.add_vertex(g,l)
Enum.each(deps, fn d -> add_dependency(g,l,d) end)
end)
if t = :digraph_utils.topsort(g) do
print_path(t)
else
IO.puts "Unsortable contains circular dependencies:"
Enum.each(:digraph.vertices(g), fn v ->
if vs = :digraph.get_short_cycle(g,v), do: print_path(vs)
end)
end
end
defp print_path(l), do: IO.puts Enum.join(l, " -> ")
defp add_dependency(_g,l,l), do: :ok
defp add_dependency(g,l,d) do
:digraph.add_vertex(g,d)
:digraph.add_edge(g,d,l)
end
end
libraries = [
des_system_lib: ~w[std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]a,
dw01: ~w[ieee dw01 dware gtech]a,
dw02: ~w[ieee dw02 dware]a,
dw03: ~w[std synopsys dware dw03 dw02 dw01 ieee gtech]a,
dw04: ~w[dw04 ieee dw01 dware gtech]a,
dw05: ~w[dw05 ieee dware]a,
dw06: ~w[dw06 ieee dware]a,
dw07: ~w[ieee dware]a,
dware: ~w[ieee dware]a,
gtech: ~w[ieee gtech]a,
ramlib: ~w[std ieee]a,
std_cell_lib: ~w[ieee std_cell_lib]a,
synopsys: []
]
Topological.sort(libraries)
IO.puts ""
bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1])
Topological.sort(bad_libraries)
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Write the same algorithm in VB as shown in this Elixir implementation. | defmodule Topological do
def sort(library) do
g = :digraph.new
Enum.each(library, fn {l,deps} ->
:digraph.add_vertex(g,l)
Enum.each(deps, fn d -> add_dependency(g,l,d) end)
end)
if t = :digraph_utils.topsort(g) do
print_path(t)
else
IO.puts "Unsortable contains circular dependencies:"
Enum.each(:digraph.vertices(g), fn v ->
if vs = :digraph.get_short_cycle(g,v), do: print_path(vs)
end)
end
end
defp print_path(l), do: IO.puts Enum.join(l, " -> ")
defp add_dependency(_g,l,l), do: :ok
defp add_dependency(g,l,d) do
:digraph.add_vertex(g,d)
:digraph.add_edge(g,d,l)
end
end
libraries = [
des_system_lib: ~w[std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]a,
dw01: ~w[ieee dw01 dware gtech]a,
dw02: ~w[ieee dw02 dware]a,
dw03: ~w[std synopsys dware dw03 dw02 dw01 ieee gtech]a,
dw04: ~w[dw04 ieee dw01 dware gtech]a,
dw05: ~w[dw05 ieee dware]a,
dw06: ~w[dw06 ieee dware]a,
dw07: ~w[ieee dware]a,
dware: ~w[ieee dware]a,
gtech: ~w[ieee gtech]a,
ramlib: ~w[std ieee]a,
std_cell_lib: ~w[ieee std_cell_lib]a,
synopsys: []
]
Topological.sort(libraries)
IO.puts ""
bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1])
Topological.sort(bad_libraries)
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Keep all operations the same but rewrite the snippet in Go. | defmodule Topological do
def sort(library) do
g = :digraph.new
Enum.each(library, fn {l,deps} ->
:digraph.add_vertex(g,l)
Enum.each(deps, fn d -> add_dependency(g,l,d) end)
end)
if t = :digraph_utils.topsort(g) do
print_path(t)
else
IO.puts "Unsortable contains circular dependencies:"
Enum.each(:digraph.vertices(g), fn v ->
if vs = :digraph.get_short_cycle(g,v), do: print_path(vs)
end)
end
end
defp print_path(l), do: IO.puts Enum.join(l, " -> ")
defp add_dependency(_g,l,l), do: :ok
defp add_dependency(g,l,d) do
:digraph.add_vertex(g,d)
:digraph.add_edge(g,d,l)
end
end
libraries = [
des_system_lib: ~w[std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]a,
dw01: ~w[ieee dw01 dware gtech]a,
dw02: ~w[ieee dw02 dware]a,
dw03: ~w[std synopsys dware dw03 dw02 dw01 ieee gtech]a,
dw04: ~w[dw04 ieee dw01 dware gtech]a,
dw05: ~w[dw05 ieee dware]a,
dw06: ~w[dw06 ieee dware]a,
dw07: ~w[ieee dware]a,
dware: ~w[ieee dware]a,
gtech: ~w[ieee gtech]a,
ramlib: ~w[std ieee]a,
std_cell_lib: ~w[ieee std_cell_lib]a,
synopsys: []
]
Topological.sort(libraries)
IO.puts ""
bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1])
Topological.sort(bad_libraries)
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Please provide an equivalent version of this Erlang code in C. | -module(topological_sort).
-compile(export_all).
-define(LIBRARIES,
[{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, []}]).
-define(BAD_LIBRARIES,
[{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]},
{dw01, [ieee, dw01, dw04, 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, []}]).
main() ->
top_sort(?LIBRARIES),
top_sort(?BAD_LIBRARIES).
top_sort(Library) ->
G = digraph:new(),
lists:foreach(fun ({L,Deps}) ->
digraph:add_vertex(G,L),
lists:foreach(fun (D) ->
add_dependency(G,L,D)
end, Deps)
end, Library),
T = digraph_utils:topsort(G),
case T of
false ->
io:format("Unsortable contains circular dependencies:~n",[]),
lists:foreach(fun (V) ->
case digraph:get_short_cycle(G,V) of
false ->
ok;
Vs ->
print_path(Vs)
end
end, digraph:vertices(G));
_ ->
print_path(T)
end.
print_path(L) ->
lists:foreach(fun (V) -> io:format("~s -> ",[V]) end,
lists:sublist(L,length(L)-1)),
io:format("~s~n",[lists:last(L)]).
add_dependency(_G,_L,_L) ->
ok;
add_dependency(G,L,D) ->
digraph:add_vertex(G,D),
digraph:add_edge(G,D,L).
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | -module(topological_sort).
-compile(export_all).
-define(LIBRARIES,
[{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, []}]).
-define(BAD_LIBRARIES,
[{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]},
{dw01, [ieee, dw01, dw04, 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, []}]).
main() ->
top_sort(?LIBRARIES),
top_sort(?BAD_LIBRARIES).
top_sort(Library) ->
G = digraph:new(),
lists:foreach(fun ({L,Deps}) ->
digraph:add_vertex(G,L),
lists:foreach(fun (D) ->
add_dependency(G,L,D)
end, Deps)
end, Library),
T = digraph_utils:topsort(G),
case T of
false ->
io:format("Unsortable contains circular dependencies:~n",[]),
lists:foreach(fun (V) ->
case digraph:get_short_cycle(G,V) of
false ->
ok;
Vs ->
print_path(Vs)
end
end, digraph:vertices(G));
_ ->
print_path(T)
end.
print_path(L) ->
lists:foreach(fun (V) -> io:format("~s -> ",[V]) end,
lists:sublist(L,length(L)-1)),
io:format("~s~n",[lists:last(L)]).
add_dependency(_G,_L,_L) ->
ok;
add_dependency(G,L,D) ->
digraph:add_vertex(G,D),
digraph:add_edge(G,D,L).
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Erlang version. | -module(topological_sort).
-compile(export_all).
-define(LIBRARIES,
[{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, []}]).
-define(BAD_LIBRARIES,
[{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]},
{dw01, [ieee, dw01, dw04, 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, []}]).
main() ->
top_sort(?LIBRARIES),
top_sort(?BAD_LIBRARIES).
top_sort(Library) ->
G = digraph:new(),
lists:foreach(fun ({L,Deps}) ->
digraph:add_vertex(G,L),
lists:foreach(fun (D) ->
add_dependency(G,L,D)
end, Deps)
end, Library),
T = digraph_utils:topsort(G),
case T of
false ->
io:format("Unsortable contains circular dependencies:~n",[]),
lists:foreach(fun (V) ->
case digraph:get_short_cycle(G,V) of
false ->
ok;
Vs ->
print_path(Vs)
end
end, digraph:vertices(G));
_ ->
print_path(T)
end.
print_path(L) ->
lists:foreach(fun (V) -> io:format("~s -> ",[V]) end,
lists:sublist(L,length(L)-1)),
io:format("~s~n",[lists:last(L)]).
add_dependency(_G,_L,_L) ->
ok;
add_dependency(G,L,D) ->
digraph:add_vertex(G,D),
digraph:add_edge(G,D,L).
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Ensure the translated Java code behaves exactly like the original Erlang snippet. | -module(topological_sort).
-compile(export_all).
-define(LIBRARIES,
[{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, []}]).
-define(BAD_LIBRARIES,
[{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]},
{dw01, [ieee, dw01, dw04, 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, []}]).
main() ->
top_sort(?LIBRARIES),
top_sort(?BAD_LIBRARIES).
top_sort(Library) ->
G = digraph:new(),
lists:foreach(fun ({L,Deps}) ->
digraph:add_vertex(G,L),
lists:foreach(fun (D) ->
add_dependency(G,L,D)
end, Deps)
end, Library),
T = digraph_utils:topsort(G),
case T of
false ->
io:format("Unsortable contains circular dependencies:~n",[]),
lists:foreach(fun (V) ->
case digraph:get_short_cycle(G,V) of
false ->
ok;
Vs ->
print_path(Vs)
end
end, digraph:vertices(G));
_ ->
print_path(T)
end.
print_path(L) ->
lists:foreach(fun (V) -> io:format("~s -> ",[V]) end,
lists:sublist(L,length(L)-1)),
io:format("~s~n",[lists:last(L)]).
add_dependency(_G,_L,_L) ->
ok;
add_dependency(G,L,D) ->
digraph:add_vertex(G,D),
digraph:add_edge(G,D,L).
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | -module(topological_sort).
-compile(export_all).
-define(LIBRARIES,
[{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, []}]).
-define(BAD_LIBRARIES,
[{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]},
{dw01, [ieee, dw01, dw04, 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, []}]).
main() ->
top_sort(?LIBRARIES),
top_sort(?BAD_LIBRARIES).
top_sort(Library) ->
G = digraph:new(),
lists:foreach(fun ({L,Deps}) ->
digraph:add_vertex(G,L),
lists:foreach(fun (D) ->
add_dependency(G,L,D)
end, Deps)
end, Library),
T = digraph_utils:topsort(G),
case T of
false ->
io:format("Unsortable contains circular dependencies:~n",[]),
lists:foreach(fun (V) ->
case digraph:get_short_cycle(G,V) of
false ->
ok;
Vs ->
print_path(Vs)
end
end, digraph:vertices(G));
_ ->
print_path(T)
end.
print_path(L) ->
lists:foreach(fun (V) -> io:format("~s -> ",[V]) end,
lists:sublist(L,length(L)-1)),
io:format("~s~n",[lists:last(L)]).
add_dependency(_G,_L,_L) ->
ok;
add_dependency(G,L,D) ->
digraph:add_vertex(G,D),
digraph:add_edge(G,D,L).
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Rewrite the snippet below in VB so it works the same as the original Erlang code. | -module(topological_sort).
-compile(export_all).
-define(LIBRARIES,
[{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, []}]).
-define(BAD_LIBRARIES,
[{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]},
{dw01, [ieee, dw01, dw04, 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, []}]).
main() ->
top_sort(?LIBRARIES),
top_sort(?BAD_LIBRARIES).
top_sort(Library) ->
G = digraph:new(),
lists:foreach(fun ({L,Deps}) ->
digraph:add_vertex(G,L),
lists:foreach(fun (D) ->
add_dependency(G,L,D)
end, Deps)
end, Library),
T = digraph_utils:topsort(G),
case T of
false ->
io:format("Unsortable contains circular dependencies:~n",[]),
lists:foreach(fun (V) ->
case digraph:get_short_cycle(G,V) of
false ->
ok;
Vs ->
print_path(Vs)
end
end, digraph:vertices(G));
_ ->
print_path(T)
end.
print_path(L) ->
lists:foreach(fun (V) -> io:format("~s -> ",[V]) end,
lists:sublist(L,length(L)-1)),
io:format("~s~n",[lists:last(L)]).
add_dependency(_G,_L,_L) ->
ok;
add_dependency(G,L,D) ->
digraph:add_vertex(G,D),
digraph:add_edge(G,D,L).
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Convert this Erlang block to Go, preserving its control flow and logic. | -module(topological_sort).
-compile(export_all).
-define(LIBRARIES,
[{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, []}]).
-define(BAD_LIBRARIES,
[{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]},
{dw01, [ieee, dw01, dw04, 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, []}]).
main() ->
top_sort(?LIBRARIES),
top_sort(?BAD_LIBRARIES).
top_sort(Library) ->
G = digraph:new(),
lists:foreach(fun ({L,Deps}) ->
digraph:add_vertex(G,L),
lists:foreach(fun (D) ->
add_dependency(G,L,D)
end, Deps)
end, Library),
T = digraph_utils:topsort(G),
case T of
false ->
io:format("Unsortable contains circular dependencies:~n",[]),
lists:foreach(fun (V) ->
case digraph:get_short_cycle(G,V) of
false ->
ok;
Vs ->
print_path(Vs)
end
end, digraph:vertices(G));
_ ->
print_path(T)
end.
print_path(L) ->
lists:foreach(fun (V) -> io:format("~s -> ",[V]) end,
lists:sublist(L,length(L)-1)),
io:format("~s~n",[lists:last(L)]).
add_dependency(_G,_L,_L) ->
ok;
add_dependency(G,L,D) ->
digraph:add_vertex(G,D),
digraph:add_edge(G,D,L).
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Maintain the same structure and functionality when rewriting this code in C. | variable nodes 0 nodes !
: node.
body> >name name>string type ;
: nodeps
['] drop over ! node. space ;
: processing
2dup <> if
['] drop over !
." " 2drop r>
then drop ;
: >processing
['] processing over ! ;
: node
create
['] nodeps ,
nodes @ , lastxt nodes !
does>
dup @ execute ;
: define-nodes
begin
parse-name dup while
2dup find-name 0= if
2dup nextname node then
2drop repeat
2drop ;
: deps
>in @ define-nodes >in !
' :noname ]] >processing [[ source >in @ /string evaluate ]] nodeps ; [[
swap >body ! 0 parse 2drop ;
: all-nodes
nodes begin
@ dup while
dup execute
>body cell+ repeat
drop ;
deps des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
deps dw01 ieee dw01 dware gtech
deps dw02 ieee dw02 dware
deps dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
deps dw04 dw04 ieee dw01 dware gtech
deps dw05 dw05 ieee dware
deps dw06 dw06 ieee dware
deps dw07 ieee dware
deps dware ieee dware
deps gtech ieee gtech
deps ramlib std ieee
deps std_cell_lib ieee std_cell_lib
deps synopsys
deps dw01 ieee dw01 dware gtech dw04
all-nodes
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Generate a C# translation of this Forth snippet without changing its computational steps. | variable nodes 0 nodes !
: node.
body> >name name>string type ;
: nodeps
['] drop over ! node. space ;
: processing
2dup <> if
['] drop over !
." " 2drop r>
then drop ;
: >processing
['] processing over ! ;
: node
create
['] nodeps ,
nodes @ , lastxt nodes !
does>
dup @ execute ;
: define-nodes
begin
parse-name dup while
2dup find-name 0= if
2dup nextname node then
2drop repeat
2drop ;
: deps
>in @ define-nodes >in !
' :noname ]] >processing [[ source >in @ /string evaluate ]] nodeps ; [[
swap >body ! 0 parse 2drop ;
: all-nodes
nodes begin
@ dup while
dup execute
>body cell+ repeat
drop ;
deps des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
deps dw01 ieee dw01 dware gtech
deps dw02 ieee dw02 dware
deps dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
deps dw04 dw04 ieee dw01 dware gtech
deps dw05 dw05 ieee dware
deps dw06 dw06 ieee dware
deps dw07 ieee dware
deps dware ieee dware
deps gtech ieee gtech
deps ramlib std ieee
deps std_cell_lib ieee std_cell_lib
deps synopsys
deps dw01 ieee dw01 dware gtech dw04
all-nodes
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Produce a functionally identical C++ code for the snippet given in Forth. | variable nodes 0 nodes !
: node.
body> >name name>string type ;
: nodeps
['] drop over ! node. space ;
: processing
2dup <> if
['] drop over !
." " 2drop r>
then drop ;
: >processing
['] processing over ! ;
: node
create
['] nodeps ,
nodes @ , lastxt nodes !
does>
dup @ execute ;
: define-nodes
begin
parse-name dup while
2dup find-name 0= if
2dup nextname node then
2drop repeat
2drop ;
: deps
>in @ define-nodes >in !
' :noname ]] >processing [[ source >in @ /string evaluate ]] nodeps ; [[
swap >body ! 0 parse 2drop ;
: all-nodes
nodes begin
@ dup while
dup execute
>body cell+ repeat
drop ;
deps des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
deps dw01 ieee dw01 dware gtech
deps dw02 ieee dw02 dware
deps dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
deps dw04 dw04 ieee dw01 dware gtech
deps dw05 dw05 ieee dware
deps dw06 dw06 ieee dware
deps dw07 ieee dware
deps dware ieee dware
deps gtech ieee gtech
deps ramlib std ieee
deps std_cell_lib ieee std_cell_lib
deps synopsys
deps dw01 ieee dw01 dware gtech dw04
all-nodes
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Preserve the algorithm and functionality while converting the code from Forth to Java. | variable nodes 0 nodes !
: node.
body> >name name>string type ;
: nodeps
['] drop over ! node. space ;
: processing
2dup <> if
['] drop over !
." " 2drop r>
then drop ;
: >processing
['] processing over ! ;
: node
create
['] nodeps ,
nodes @ , lastxt nodes !
does>
dup @ execute ;
: define-nodes
begin
parse-name dup while
2dup find-name 0= if
2dup nextname node then
2drop repeat
2drop ;
: deps
>in @ define-nodes >in !
' :noname ]] >processing [[ source >in @ /string evaluate ]] nodeps ; [[
swap >body ! 0 parse 2drop ;
: all-nodes
nodes begin
@ dup while
dup execute
>body cell+ repeat
drop ;
deps des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
deps dw01 ieee dw01 dware gtech
deps dw02 ieee dw02 dware
deps dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
deps dw04 dw04 ieee dw01 dware gtech
deps dw05 dw05 ieee dware
deps dw06 dw06 ieee dware
deps dw07 ieee dware
deps dware ieee dware
deps gtech ieee gtech
deps ramlib std ieee
deps std_cell_lib ieee std_cell_lib
deps synopsys
deps dw01 ieee dw01 dware gtech dw04
all-nodes
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Produce a functionally identical Python code for the snippet given in Forth. | variable nodes 0 nodes !
: node.
body> >name name>string type ;
: nodeps
['] drop over ! node. space ;
: processing
2dup <> if
['] drop over !
." " 2drop r>
then drop ;
: >processing
['] processing over ! ;
: node
create
['] nodeps ,
nodes @ , lastxt nodes !
does>
dup @ execute ;
: define-nodes
begin
parse-name dup while
2dup find-name 0= if
2dup nextname node then
2drop repeat
2drop ;
: deps
>in @ define-nodes >in !
' :noname ]] >processing [[ source >in @ /string evaluate ]] nodeps ; [[
swap >body ! 0 parse 2drop ;
: all-nodes
nodes begin
@ dup while
dup execute
>body cell+ repeat
drop ;
deps des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
deps dw01 ieee dw01 dware gtech
deps dw02 ieee dw02 dware
deps dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
deps dw04 dw04 ieee dw01 dware gtech
deps dw05 dw05 ieee dware
deps dw06 dw06 ieee dware
deps dw07 ieee dware
deps dware ieee dware
deps gtech ieee gtech
deps ramlib std ieee
deps std_cell_lib ieee std_cell_lib
deps synopsys
deps dw01 ieee dw01 dware gtech dw04
all-nodes
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Ensure the translated VB code behaves exactly like the original Forth snippet. | variable nodes 0 nodes !
: node.
body> >name name>string type ;
: nodeps
['] drop over ! node. space ;
: processing
2dup <> if
['] drop over !
." " 2drop r>
then drop ;
: >processing
['] processing over ! ;
: node
create
['] nodeps ,
nodes @ , lastxt nodes !
does>
dup @ execute ;
: define-nodes
begin
parse-name dup while
2dup find-name 0= if
2dup nextname node then
2drop repeat
2drop ;
: deps
>in @ define-nodes >in !
' :noname ]] >processing [[ source >in @ /string evaluate ]] nodeps ; [[
swap >body ! 0 parse 2drop ;
: all-nodes
nodes begin
@ dup while
dup execute
>body cell+ repeat
drop ;
deps des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
deps dw01 ieee dw01 dware gtech
deps dw02 ieee dw02 dware
deps dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
deps dw04 dw04 ieee dw01 dware gtech
deps dw05 dw05 ieee dware
deps dw06 dw06 ieee dware
deps dw07 ieee dware
deps dware ieee dware
deps gtech ieee gtech
deps ramlib std ieee
deps std_cell_lib ieee std_cell_lib
deps synopsys
deps dw01 ieee dw01 dware gtech dw04
all-nodes
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Generate a Go translation of this Forth snippet without changing its computational steps. | variable nodes 0 nodes !
: node.
body> >name name>string type ;
: nodeps
['] drop over ! node. space ;
: processing
2dup <> if
['] drop over !
." " 2drop r>
then drop ;
: >processing
['] processing over ! ;
: node
create
['] nodeps ,
nodes @ , lastxt nodes !
does>
dup @ execute ;
: define-nodes
begin
parse-name dup while
2dup find-name 0= if
2dup nextname node then
2drop repeat
2drop ;
: deps
>in @ define-nodes >in !
' :noname ]] >processing [[ source >in @ /string evaluate ]] nodeps ; [[
swap >body ! 0 parse 2drop ;
: all-nodes
nodes begin
@ dup while
dup execute
>body cell+ repeat
drop ;
deps des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
deps dw01 ieee dw01 dware gtech
deps dw02 ieee dw02 dware
deps dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
deps dw04 dw04 ieee dw01 dware gtech
deps dw05 dw05 ieee dware
deps dw06 dw06 ieee dware
deps dw07 ieee dware
deps dware ieee dware
deps gtech ieee gtech
deps ramlib std ieee
deps std_cell_lib ieee std_cell_lib
deps synopsys
deps dw01 ieee dw01 dware gtech dw04
all-nodes
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Change the following Fortran code into C# without altering its purpose. | 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
DO 10 I=1,NL
IORD(I)=I
10 IPOS(I)=I
K=1
20 J=K
K=NL+1
DO 30 I=1,ND
IL=IDEP(I,1)
IR=IDEP(I,2)
IPL=IPOS(IL)
IPR=IPOS(IR)
IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30
K=K-1
IPOS(IORD(K))=IPL
IPOS(IL)=K
IORD(IPL)=IORD(K)
IORD(K)=IL
30 CONTINUE
IF(K.GT.J) GO TO 20
NO=J-1
END
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Generate a C++ translation of this Fortran snippet without changing its computational steps. | 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
DO 10 I=1,NL
IORD(I)=I
10 IPOS(I)=I
K=1
20 J=K
K=NL+1
DO 30 I=1,ND
IL=IDEP(I,1)
IR=IDEP(I,2)
IPL=IPOS(IL)
IPR=IPOS(IR)
IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30
K=K-1
IPOS(IORD(K))=IPL
IPOS(IL)=K
IORD(IPL)=IORD(K)
IORD(K)=IL
30 CONTINUE
IF(K.GT.J) GO TO 20
NO=J-1
END
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Port the provided Fortran code into C while preserving the original functionality. | 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
DO 10 I=1,NL
IORD(I)=I
10 IPOS(I)=I
K=1
20 J=K
K=NL+1
DO 30 I=1,ND
IL=IDEP(I,1)
IR=IDEP(I,2)
IPL=IPOS(IL)
IPR=IPOS(IR)
IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30
K=K-1
IPOS(IORD(K))=IPL
IPOS(IL)=K
IORD(IPL)=IORD(K)
IORD(K)=IL
30 CONTINUE
IF(K.GT.J) GO TO 20
NO=J-1
END
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Write the same code in Go as shown below in 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
DO 10 I=1,NL
IORD(I)=I
10 IPOS(I)=I
K=1
20 J=K
K=NL+1
DO 30 I=1,ND
IL=IDEP(I,1)
IR=IDEP(I,2)
IPL=IPOS(IL)
IPR=IPOS(IR)
IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30
K=K-1
IPOS(IORD(K))=IPL
IPOS(IL)=K
IORD(IPL)=IORD(K)
IORD(K)=IL
30 CONTINUE
IF(K.GT.J) GO TO 20
NO=J-1
END
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Preserve the algorithm and functionality while converting the code from Fortran to Java. | 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
DO 10 I=1,NL
IORD(I)=I
10 IPOS(I)=I
K=1
20 J=K
K=NL+1
DO 30 I=1,ND
IL=IDEP(I,1)
IR=IDEP(I,2)
IPL=IPOS(IL)
IPR=IPOS(IR)
IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30
K=K-1
IPOS(IORD(K))=IPL
IPOS(IL)=K
IORD(IPL)=IORD(K)
IORD(K)=IL
30 CONTINUE
IF(K.GT.J) GO TO 20
NO=J-1
END
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Port the provided Fortran code into Python while preserving the original functionality. | 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
DO 10 I=1,NL
IORD(I)=I
10 IPOS(I)=I
K=1
20 J=K
K=NL+1
DO 30 I=1,ND
IL=IDEP(I,1)
IR=IDEP(I,2)
IPL=IPOS(IL)
IPR=IPOS(IR)
IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30
K=K-1
IPOS(IORD(K))=IPL
IPOS(IL)=K
IORD(IPL)=IORD(K)
IORD(K)=IL
30 CONTINUE
IF(K.GT.J) GO TO 20
NO=J-1
END
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Convert this Fortran block to VB, preserving its control flow and logic. | 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
DO 10 I=1,NL
IORD(I)=I
10 IPOS(I)=I
K=1
20 J=K
K=NL+1
DO 30 I=1,ND
IL=IDEP(I,1)
IR=IDEP(I,2)
IPL=IPOS(IL)
IPR=IPOS(IR)
IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30
K=K-1
IPOS(IORD(K))=IPL
IPOS(IL)=K
IORD(IPL)=IORD(K)
IORD(K)=IL
30 CONTINUE
IF(K.GT.J) GO TO 20
NO=J-1
END
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Write a version of this Haskell function in C with identical behavior. | import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "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", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Transform the following Haskell implementation into C#, maintaining the same output and logic. | import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "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", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Write the same algorithm in C++ as shown in this Haskell implementation. | import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "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", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Ensure the translated Java code behaves exactly like the original Haskell snippet. | import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "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", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Produce a functionally identical Python code for the snippet given in Haskell. | import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "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", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Produce a language-to-language conversion: from Haskell to VB, same semantics. | import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "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", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Maintain the same structure and functionality when rewriting this code in Go. | import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "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", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Rewrite this program in C while keeping its functionality equivalent to the Icon version. | record graph(nodes,arcs)
global ex_name, in_name
procedure main()
show(tsort(getgraph()))
end
procedure tsort(g)
t := ""
while (n := g.nodes -- pnodes(g)) ~== "" do {
t ||:= "("||n||")"
g := delete(g,n)
}
if g.nodes == '' then return t
write("graph contains the cycle:")
write("\t",genpath(fn := !g.nodes,fn,g))
end
procedure pnodes(g)
static labels, fromnodes
initial {
labels := &ucase
fromnodes := 'ACEGIKMOQSUWY'
}
return cset(select(g.arcs,labels, fromnodes))
end
procedure select(s,image,object)
slen := *s
ilen := *image
return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s)
else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object)
end
procedure delete(g,x)
t := ""
g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc
return graph(g.nodes--x,t)
end
procedure getgraph()
static labels
initial labels := &cset
ex_name := table()
in_name := table()
count := 0
arcstr := ""
nodes := ''
every line := !&input do {
nextWord := create genWords(line)
if nfrom := @nextWord then {
/in_name[nfrom] := &cset[count +:= 1]
/ex_name[in_name[nfrom]] := nfrom
nodes ++:= in_name[nfrom]
while nto := @nextWord do {
if nfrom ~== nto then {
/in_name[nto] := &cset[count +:= 1]
/ex_name[in_name[nto]] := nto
nodes ++:= in_name[nto]
arcstr ||:= in_name[nfrom] || in_name[nto]
}
}
}
}
return graph(nodes,arcstr)
end
procedure genWords(s)
static wchars
initial wchars := &cset -- ' \t'
s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1
end
procedure show(t)
line := ""
every n := !t do
case n of {
"(" : line ||:= "\n\t("
")" : line[-1] := ")"
default : line ||:= ex_name[n] || " "
}
write(line)
end
procedure genpath(f,t,g, seen)
/seen := ''
seen ++:= f
sn := nnodes(f,g)
if t ** sn == t then return ex_name[f] || " -> " || ex_name[t]
suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen)
end
procedure nnodes(f,g)
t := ''
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Change the following Icon code into C# without altering its purpose. | record graph(nodes,arcs)
global ex_name, in_name
procedure main()
show(tsort(getgraph()))
end
procedure tsort(g)
t := ""
while (n := g.nodes -- pnodes(g)) ~== "" do {
t ||:= "("||n||")"
g := delete(g,n)
}
if g.nodes == '' then return t
write("graph contains the cycle:")
write("\t",genpath(fn := !g.nodes,fn,g))
end
procedure pnodes(g)
static labels, fromnodes
initial {
labels := &ucase
fromnodes := 'ACEGIKMOQSUWY'
}
return cset(select(g.arcs,labels, fromnodes))
end
procedure select(s,image,object)
slen := *s
ilen := *image
return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s)
else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object)
end
procedure delete(g,x)
t := ""
g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc
return graph(g.nodes--x,t)
end
procedure getgraph()
static labels
initial labels := &cset
ex_name := table()
in_name := table()
count := 0
arcstr := ""
nodes := ''
every line := !&input do {
nextWord := create genWords(line)
if nfrom := @nextWord then {
/in_name[nfrom] := &cset[count +:= 1]
/ex_name[in_name[nfrom]] := nfrom
nodes ++:= in_name[nfrom]
while nto := @nextWord do {
if nfrom ~== nto then {
/in_name[nto] := &cset[count +:= 1]
/ex_name[in_name[nto]] := nto
nodes ++:= in_name[nto]
arcstr ||:= in_name[nfrom] || in_name[nto]
}
}
}
}
return graph(nodes,arcstr)
end
procedure genWords(s)
static wchars
initial wchars := &cset -- ' \t'
s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1
end
procedure show(t)
line := ""
every n := !t do
case n of {
"(" : line ||:= "\n\t("
")" : line[-1] := ")"
default : line ||:= ex_name[n] || " "
}
write(line)
end
procedure genpath(f,t,g, seen)
/seen := ''
seen ++:= f
sn := nnodes(f,g)
if t ** sn == t then return ex_name[f] || " -> " || ex_name[t]
suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen)
end
procedure nnodes(f,g)
t := ''
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Translate this program into C++ but keep the logic exactly as in Icon. | record graph(nodes,arcs)
global ex_name, in_name
procedure main()
show(tsort(getgraph()))
end
procedure tsort(g)
t := ""
while (n := g.nodes -- pnodes(g)) ~== "" do {
t ||:= "("||n||")"
g := delete(g,n)
}
if g.nodes == '' then return t
write("graph contains the cycle:")
write("\t",genpath(fn := !g.nodes,fn,g))
end
procedure pnodes(g)
static labels, fromnodes
initial {
labels := &ucase
fromnodes := 'ACEGIKMOQSUWY'
}
return cset(select(g.arcs,labels, fromnodes))
end
procedure select(s,image,object)
slen := *s
ilen := *image
return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s)
else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object)
end
procedure delete(g,x)
t := ""
g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc
return graph(g.nodes--x,t)
end
procedure getgraph()
static labels
initial labels := &cset
ex_name := table()
in_name := table()
count := 0
arcstr := ""
nodes := ''
every line := !&input do {
nextWord := create genWords(line)
if nfrom := @nextWord then {
/in_name[nfrom] := &cset[count +:= 1]
/ex_name[in_name[nfrom]] := nfrom
nodes ++:= in_name[nfrom]
while nto := @nextWord do {
if nfrom ~== nto then {
/in_name[nto] := &cset[count +:= 1]
/ex_name[in_name[nto]] := nto
nodes ++:= in_name[nto]
arcstr ||:= in_name[nfrom] || in_name[nto]
}
}
}
}
return graph(nodes,arcstr)
end
procedure genWords(s)
static wchars
initial wchars := &cset -- ' \t'
s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1
end
procedure show(t)
line := ""
every n := !t do
case n of {
"(" : line ||:= "\n\t("
")" : line[-1] := ")"
default : line ||:= ex_name[n] || " "
}
write(line)
end
procedure genpath(f,t,g, seen)
/seen := ''
seen ++:= f
sn := nnodes(f,g)
if t ** sn == t then return ex_name[f] || " -> " || ex_name[t]
suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen)
end
procedure nnodes(f,g)
t := ''
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Produce a functionally identical Java code for the snippet given in Icon. | record graph(nodes,arcs)
global ex_name, in_name
procedure main()
show(tsort(getgraph()))
end
procedure tsort(g)
t := ""
while (n := g.nodes -- pnodes(g)) ~== "" do {
t ||:= "("||n||")"
g := delete(g,n)
}
if g.nodes == '' then return t
write("graph contains the cycle:")
write("\t",genpath(fn := !g.nodes,fn,g))
end
procedure pnodes(g)
static labels, fromnodes
initial {
labels := &ucase
fromnodes := 'ACEGIKMOQSUWY'
}
return cset(select(g.arcs,labels, fromnodes))
end
procedure select(s,image,object)
slen := *s
ilen := *image
return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s)
else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object)
end
procedure delete(g,x)
t := ""
g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc
return graph(g.nodes--x,t)
end
procedure getgraph()
static labels
initial labels := &cset
ex_name := table()
in_name := table()
count := 0
arcstr := ""
nodes := ''
every line := !&input do {
nextWord := create genWords(line)
if nfrom := @nextWord then {
/in_name[nfrom] := &cset[count +:= 1]
/ex_name[in_name[nfrom]] := nfrom
nodes ++:= in_name[nfrom]
while nto := @nextWord do {
if nfrom ~== nto then {
/in_name[nto] := &cset[count +:= 1]
/ex_name[in_name[nto]] := nto
nodes ++:= in_name[nto]
arcstr ||:= in_name[nfrom] || in_name[nto]
}
}
}
}
return graph(nodes,arcstr)
end
procedure genWords(s)
static wchars
initial wchars := &cset -- ' \t'
s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1
end
procedure show(t)
line := ""
every n := !t do
case n of {
"(" : line ||:= "\n\t("
")" : line[-1] := ")"
default : line ||:= ex_name[n] || " "
}
write(line)
end
procedure genpath(f,t,g, seen)
/seen := ''
seen ++:= f
sn := nnodes(f,g)
if t ** sn == t then return ex_name[f] || " -> " || ex_name[t]
suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen)
end
procedure nnodes(f,g)
t := ''
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Change the programming language of this snippet from Icon to Python without modifying what it does. | record graph(nodes,arcs)
global ex_name, in_name
procedure main()
show(tsort(getgraph()))
end
procedure tsort(g)
t := ""
while (n := g.nodes -- pnodes(g)) ~== "" do {
t ||:= "("||n||")"
g := delete(g,n)
}
if g.nodes == '' then return t
write("graph contains the cycle:")
write("\t",genpath(fn := !g.nodes,fn,g))
end
procedure pnodes(g)
static labels, fromnodes
initial {
labels := &ucase
fromnodes := 'ACEGIKMOQSUWY'
}
return cset(select(g.arcs,labels, fromnodes))
end
procedure select(s,image,object)
slen := *s
ilen := *image
return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s)
else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object)
end
procedure delete(g,x)
t := ""
g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc
return graph(g.nodes--x,t)
end
procedure getgraph()
static labels
initial labels := &cset
ex_name := table()
in_name := table()
count := 0
arcstr := ""
nodes := ''
every line := !&input do {
nextWord := create genWords(line)
if nfrom := @nextWord then {
/in_name[nfrom] := &cset[count +:= 1]
/ex_name[in_name[nfrom]] := nfrom
nodes ++:= in_name[nfrom]
while nto := @nextWord do {
if nfrom ~== nto then {
/in_name[nto] := &cset[count +:= 1]
/ex_name[in_name[nto]] := nto
nodes ++:= in_name[nto]
arcstr ||:= in_name[nfrom] || in_name[nto]
}
}
}
}
return graph(nodes,arcstr)
end
procedure genWords(s)
static wchars
initial wchars := &cset -- ' \t'
s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1
end
procedure show(t)
line := ""
every n := !t do
case n of {
"(" : line ||:= "\n\t("
")" : line[-1] := ")"
default : line ||:= ex_name[n] || " "
}
write(line)
end
procedure genpath(f,t,g, seen)
/seen := ''
seen ++:= f
sn := nnodes(f,g)
if t ** sn == t then return ex_name[f] || " -> " || ex_name[t]
suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen)
end
procedure nnodes(f,g)
t := ''
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Change the programming language of this snippet from Icon to VB without modifying what it does. | record graph(nodes,arcs)
global ex_name, in_name
procedure main()
show(tsort(getgraph()))
end
procedure tsort(g)
t := ""
while (n := g.nodes -- pnodes(g)) ~== "" do {
t ||:= "("||n||")"
g := delete(g,n)
}
if g.nodes == '' then return t
write("graph contains the cycle:")
write("\t",genpath(fn := !g.nodes,fn,g))
end
procedure pnodes(g)
static labels, fromnodes
initial {
labels := &ucase
fromnodes := 'ACEGIKMOQSUWY'
}
return cset(select(g.arcs,labels, fromnodes))
end
procedure select(s,image,object)
slen := *s
ilen := *image
return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s)
else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object)
end
procedure delete(g,x)
t := ""
g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc
return graph(g.nodes--x,t)
end
procedure getgraph()
static labels
initial labels := &cset
ex_name := table()
in_name := table()
count := 0
arcstr := ""
nodes := ''
every line := !&input do {
nextWord := create genWords(line)
if nfrom := @nextWord then {
/in_name[nfrom] := &cset[count +:= 1]
/ex_name[in_name[nfrom]] := nfrom
nodes ++:= in_name[nfrom]
while nto := @nextWord do {
if nfrom ~== nto then {
/in_name[nto] := &cset[count +:= 1]
/ex_name[in_name[nto]] := nto
nodes ++:= in_name[nto]
arcstr ||:= in_name[nfrom] || in_name[nto]
}
}
}
}
return graph(nodes,arcstr)
end
procedure genWords(s)
static wchars
initial wchars := &cset -- ' \t'
s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1
end
procedure show(t)
line := ""
every n := !t do
case n of {
"(" : line ||:= "\n\t("
")" : line[-1] := ")"
default : line ||:= ex_name[n] || " "
}
write(line)
end
procedure genpath(f,t,g, seen)
/seen := ''
seen ++:= f
sn := nnodes(f,g)
if t ** sn == t then return ex_name[f] || " -> " || ex_name[t]
suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen)
end
procedure nnodes(f,g)
t := ''
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Produce a functionally identical Go code for the snippet given in Icon. | record graph(nodes,arcs)
global ex_name, in_name
procedure main()
show(tsort(getgraph()))
end
procedure tsort(g)
t := ""
while (n := g.nodes -- pnodes(g)) ~== "" do {
t ||:= "("||n||")"
g := delete(g,n)
}
if g.nodes == '' then return t
write("graph contains the cycle:")
write("\t",genpath(fn := !g.nodes,fn,g))
end
procedure pnodes(g)
static labels, fromnodes
initial {
labels := &ucase
fromnodes := 'ACEGIKMOQSUWY'
}
return cset(select(g.arcs,labels, fromnodes))
end
procedure select(s,image,object)
slen := *s
ilen := *image
return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s)
else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object)
end
procedure delete(g,x)
t := ""
g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc
return graph(g.nodes--x,t)
end
procedure getgraph()
static labels
initial labels := &cset
ex_name := table()
in_name := table()
count := 0
arcstr := ""
nodes := ''
every line := !&input do {
nextWord := create genWords(line)
if nfrom := @nextWord then {
/in_name[nfrom] := &cset[count +:= 1]
/ex_name[in_name[nfrom]] := nfrom
nodes ++:= in_name[nfrom]
while nto := @nextWord do {
if nfrom ~== nto then {
/in_name[nto] := &cset[count +:= 1]
/ex_name[in_name[nto]] := nto
nodes ++:= in_name[nto]
arcstr ||:= in_name[nfrom] || in_name[nto]
}
}
}
}
return graph(nodes,arcstr)
end
procedure genWords(s)
static wchars
initial wchars := &cset -- ' \t'
s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1
end
procedure show(t)
line := ""
every n := !t do
case n of {
"(" : line ||:= "\n\t("
")" : line[-1] := ")"
default : line ||:= ex_name[n] || " "
}
write(line)
end
procedure genpath(f,t,g, seen)
/seen := ''
seen ++:= f
sn := nnodes(f,g)
if t ** sn == t then return ex_name[f] || " -> " || ex_name[t]
suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen)
end
procedure nnodes(f,g)
t := ''
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Change the programming language of this snippet from J to C without modifying what it does. | dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
depends=. (> =@i.@#) names e.S:1 parsed
depends=. (+. +./ .*.~)^:_ depends
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Write the same code in C# as shown below in J. | dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
depends=. (> =@i.@#) names e.S:1 parsed
depends=. (+. +./ .*.~)^:_ depends
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
)
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Convert this J snippet to C++ and keep its semantics consistent. | dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
depends=. (> =@i.@#) names e.S:1 parsed
depends=. (+. +./ .*.~)^:_ depends
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
)
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Keep all operations the same but rewrite the snippet in Java. | dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
depends=. (> =@i.@#) names e.S:1 parsed
depends=. (+. +./ .*.~)^:_ depends
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
)
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Translate the given J code snippet into Python without altering its behavior. | dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
depends=. (> =@i.@#) names e.S:1 parsed
depends=. (+. +./ .*.~)^:_ depends
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
)
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Preserve the algorithm and functionality while converting the code from J to VB. | dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
depends=. (> =@i.@#) names e.S:1 parsed
depends=. (+. +./ .*.~)^:_ depends
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
)
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Can you help me rewrite this code in Go instead of J, keeping it the same logically? | dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
depends=. (> =@i.@#) names e.S:1 parsed
depends=. (+. +./ .*.~)^:_ depends
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
)
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Rewrite this program in C while keeping its functionality equivalent to the Julia version. | 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("
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Rewrite the snippet below in C# so it works the same as the original Julia code. | 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("
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Generate a C++ translation of this Julia snippet without changing its computational steps. | 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("
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Write the same algorithm in Java as shown in this Julia implementation. | 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("
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Keep all operations the same but rewrite the snippet in Python. | 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("
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Port the provided Julia code into VB while preserving the original functionality. | 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("
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Transform the following Julia implementation into Go, maintaining the same output and logic. | 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("
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Convert the following code from Mathematica to C, ensuring the logic remains intact. | TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@
{{"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", {}}}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@
{{"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", {}}}
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Convert the following code from Mathematica to C++, ensuring the logic remains intact. | TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@
{{"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", {}}}
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Port the following code from Mathematica to Java with equivalent syntax and logic. | TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@
{{"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", {}}}
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Preserve the algorithm and functionality while converting the code from Mathematica to Python. | TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@
{{"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", {}}}
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Maintain the same structure and functionality when rewriting this code in VB. | TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@
{{"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", {}}}
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Produce a functionally identical Go code for the snippet given in Mathematica. | TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@
{{"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", {}}}
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Maintain the same structure and functionality when rewriting this code in C. | import sequtils, strutils, sets, tables, sugar
type StringSet = HashSet[string]
proc topSort(data: var OrderedTable[string, StringSet]) =
var ranks: Table[string, Natural]
for key, values in data.mpairs:
values.excl key
for values in toSeq(data.values):
for value in values:
if value notin data:
data[value] = initHashSet[string]()
var deps = data
var rank = 0
while deps.len > 0:
var keyToRemove: string
for key, values in deps.pairs:
if values.card == 0:
keyToRemove = key
break
if keyToRemove.len == 0:
raise newException(ValueError, "Unorderable items found: " & toSeq(deps.keys).join(", "))
ranks[keyToRemove] = rank
inc rank
deps.del keyToRemove
for k, v in deps.mpairs:
v.excl keyToRemove
data.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))
when isMainModule:
const Data = {"des_system_lib": ["std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01",
"ramlib", "ieee"].toHashSet,
"dw01": ["ieee", "dw01", "dware", "gtech"].toHashSet,
"dw02": ["ieee", "dw02", "dware"].toHashSet,
"dw03": ["std", "synopsys", "dware", "dw03",
"dw02", "dw01", "ieee", "gtech"].toHashSet,
"dw04": ["dw04", "ieee", "dw01", "dware", "gtech"].toHashSet,
"dw05": ["dw05", "ieee", "dware"].toHashSet,
"dw06": ["dw06", "ieee", "dware"].toHashSet,
"dw07": ["ieee", "dware"].toHashSet,
"dware": ["ieee", "dware"].toHashSet,
"gtech": ["ieee", "gtech"].toHashSet,
"ramlib": ["std", "ieee"].toHashSet,
"std_cell_lib": ["ieee", "std_cell_lib"].toHashSet,
"synopsys": initHashSet[string]()}.toOrderedTable
echo "Data without cycle. Order after sorting:"
var data = Data
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
echo "\nData with a cycle:"
data = Data
data["dw01"].incl "dw04"
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Convert this Nim snippet to C# and keep its semantics consistent. | import sequtils, strutils, sets, tables, sugar
type StringSet = HashSet[string]
proc topSort(data: var OrderedTable[string, StringSet]) =
var ranks: Table[string, Natural]
for key, values in data.mpairs:
values.excl key
for values in toSeq(data.values):
for value in values:
if value notin data:
data[value] = initHashSet[string]()
var deps = data
var rank = 0
while deps.len > 0:
var keyToRemove: string
for key, values in deps.pairs:
if values.card == 0:
keyToRemove = key
break
if keyToRemove.len == 0:
raise newException(ValueError, "Unorderable items found: " & toSeq(deps.keys).join(", "))
ranks[keyToRemove] = rank
inc rank
deps.del keyToRemove
for k, v in deps.mpairs:
v.excl keyToRemove
data.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))
when isMainModule:
const Data = {"des_system_lib": ["std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01",
"ramlib", "ieee"].toHashSet,
"dw01": ["ieee", "dw01", "dware", "gtech"].toHashSet,
"dw02": ["ieee", "dw02", "dware"].toHashSet,
"dw03": ["std", "synopsys", "dware", "dw03",
"dw02", "dw01", "ieee", "gtech"].toHashSet,
"dw04": ["dw04", "ieee", "dw01", "dware", "gtech"].toHashSet,
"dw05": ["dw05", "ieee", "dware"].toHashSet,
"dw06": ["dw06", "ieee", "dware"].toHashSet,
"dw07": ["ieee", "dware"].toHashSet,
"dware": ["ieee", "dware"].toHashSet,
"gtech": ["ieee", "gtech"].toHashSet,
"ramlib": ["std", "ieee"].toHashSet,
"std_cell_lib": ["ieee", "std_cell_lib"].toHashSet,
"synopsys": initHashSet[string]()}.toOrderedTable
echo "Data without cycle. Order after sorting:"
var data = Data
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
echo "\nData with a cycle:"
data = Data
data["dw01"].incl "dw04"
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Write the same code in C++ as shown below in Nim. | import sequtils, strutils, sets, tables, sugar
type StringSet = HashSet[string]
proc topSort(data: var OrderedTable[string, StringSet]) =
var ranks: Table[string, Natural]
for key, values in data.mpairs:
values.excl key
for values in toSeq(data.values):
for value in values:
if value notin data:
data[value] = initHashSet[string]()
var deps = data
var rank = 0
while deps.len > 0:
var keyToRemove: string
for key, values in deps.pairs:
if values.card == 0:
keyToRemove = key
break
if keyToRemove.len == 0:
raise newException(ValueError, "Unorderable items found: " & toSeq(deps.keys).join(", "))
ranks[keyToRemove] = rank
inc rank
deps.del keyToRemove
for k, v in deps.mpairs:
v.excl keyToRemove
data.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))
when isMainModule:
const Data = {"des_system_lib": ["std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01",
"ramlib", "ieee"].toHashSet,
"dw01": ["ieee", "dw01", "dware", "gtech"].toHashSet,
"dw02": ["ieee", "dw02", "dware"].toHashSet,
"dw03": ["std", "synopsys", "dware", "dw03",
"dw02", "dw01", "ieee", "gtech"].toHashSet,
"dw04": ["dw04", "ieee", "dw01", "dware", "gtech"].toHashSet,
"dw05": ["dw05", "ieee", "dware"].toHashSet,
"dw06": ["dw06", "ieee", "dware"].toHashSet,
"dw07": ["ieee", "dware"].toHashSet,
"dware": ["ieee", "dware"].toHashSet,
"gtech": ["ieee", "gtech"].toHashSet,
"ramlib": ["std", "ieee"].toHashSet,
"std_cell_lib": ["ieee", "std_cell_lib"].toHashSet,
"synopsys": initHashSet[string]()}.toOrderedTable
echo "Data without cycle. Order after sorting:"
var data = Data
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
echo "\nData with a cycle:"
data = Data
data["dw01"].incl "dw04"
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Transform the following Nim implementation into Java, maintaining the same output and logic. | import sequtils, strutils, sets, tables, sugar
type StringSet = HashSet[string]
proc topSort(data: var OrderedTable[string, StringSet]) =
var ranks: Table[string, Natural]
for key, values in data.mpairs:
values.excl key
for values in toSeq(data.values):
for value in values:
if value notin data:
data[value] = initHashSet[string]()
var deps = data
var rank = 0
while deps.len > 0:
var keyToRemove: string
for key, values in deps.pairs:
if values.card == 0:
keyToRemove = key
break
if keyToRemove.len == 0:
raise newException(ValueError, "Unorderable items found: " & toSeq(deps.keys).join(", "))
ranks[keyToRemove] = rank
inc rank
deps.del keyToRemove
for k, v in deps.mpairs:
v.excl keyToRemove
data.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))
when isMainModule:
const Data = {"des_system_lib": ["std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01",
"ramlib", "ieee"].toHashSet,
"dw01": ["ieee", "dw01", "dware", "gtech"].toHashSet,
"dw02": ["ieee", "dw02", "dware"].toHashSet,
"dw03": ["std", "synopsys", "dware", "dw03",
"dw02", "dw01", "ieee", "gtech"].toHashSet,
"dw04": ["dw04", "ieee", "dw01", "dware", "gtech"].toHashSet,
"dw05": ["dw05", "ieee", "dware"].toHashSet,
"dw06": ["dw06", "ieee", "dware"].toHashSet,
"dw07": ["ieee", "dware"].toHashSet,
"dware": ["ieee", "dware"].toHashSet,
"gtech": ["ieee", "gtech"].toHashSet,
"ramlib": ["std", "ieee"].toHashSet,
"std_cell_lib": ["ieee", "std_cell_lib"].toHashSet,
"synopsys": initHashSet[string]()}.toOrderedTable
echo "Data without cycle. Order after sorting:"
var data = Data
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
echo "\nData with a cycle:"
data = Data
data["dw01"].incl "dw04"
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Generate an equivalent Python version of this Nim code. | import sequtils, strutils, sets, tables, sugar
type StringSet = HashSet[string]
proc topSort(data: var OrderedTable[string, StringSet]) =
var ranks: Table[string, Natural]
for key, values in data.mpairs:
values.excl key
for values in toSeq(data.values):
for value in values:
if value notin data:
data[value] = initHashSet[string]()
var deps = data
var rank = 0
while deps.len > 0:
var keyToRemove: string
for key, values in deps.pairs:
if values.card == 0:
keyToRemove = key
break
if keyToRemove.len == 0:
raise newException(ValueError, "Unorderable items found: " & toSeq(deps.keys).join(", "))
ranks[keyToRemove] = rank
inc rank
deps.del keyToRemove
for k, v in deps.mpairs:
v.excl keyToRemove
data.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))
when isMainModule:
const Data = {"des_system_lib": ["std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01",
"ramlib", "ieee"].toHashSet,
"dw01": ["ieee", "dw01", "dware", "gtech"].toHashSet,
"dw02": ["ieee", "dw02", "dware"].toHashSet,
"dw03": ["std", "synopsys", "dware", "dw03",
"dw02", "dw01", "ieee", "gtech"].toHashSet,
"dw04": ["dw04", "ieee", "dw01", "dware", "gtech"].toHashSet,
"dw05": ["dw05", "ieee", "dware"].toHashSet,
"dw06": ["dw06", "ieee", "dware"].toHashSet,
"dw07": ["ieee", "dware"].toHashSet,
"dware": ["ieee", "dware"].toHashSet,
"gtech": ["ieee", "gtech"].toHashSet,
"ramlib": ["std", "ieee"].toHashSet,
"std_cell_lib": ["ieee", "std_cell_lib"].toHashSet,
"synopsys": initHashSet[string]()}.toOrderedTable
echo "Data without cycle. Order after sorting:"
var data = Data
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
echo "\nData with a cycle:"
data = Data
data["dw01"].incl "dw04"
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Maintain the same structure and functionality when rewriting this code in VB. | import sequtils, strutils, sets, tables, sugar
type StringSet = HashSet[string]
proc topSort(data: var OrderedTable[string, StringSet]) =
var ranks: Table[string, Natural]
for key, values in data.mpairs:
values.excl key
for values in toSeq(data.values):
for value in values:
if value notin data:
data[value] = initHashSet[string]()
var deps = data
var rank = 0
while deps.len > 0:
var keyToRemove: string
for key, values in deps.pairs:
if values.card == 0:
keyToRemove = key
break
if keyToRemove.len == 0:
raise newException(ValueError, "Unorderable items found: " & toSeq(deps.keys).join(", "))
ranks[keyToRemove] = rank
inc rank
deps.del keyToRemove
for k, v in deps.mpairs:
v.excl keyToRemove
data.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))
when isMainModule:
const Data = {"des_system_lib": ["std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01",
"ramlib", "ieee"].toHashSet,
"dw01": ["ieee", "dw01", "dware", "gtech"].toHashSet,
"dw02": ["ieee", "dw02", "dware"].toHashSet,
"dw03": ["std", "synopsys", "dware", "dw03",
"dw02", "dw01", "ieee", "gtech"].toHashSet,
"dw04": ["dw04", "ieee", "dw01", "dware", "gtech"].toHashSet,
"dw05": ["dw05", "ieee", "dware"].toHashSet,
"dw06": ["dw06", "ieee", "dware"].toHashSet,
"dw07": ["ieee", "dware"].toHashSet,
"dware": ["ieee", "dware"].toHashSet,
"gtech": ["ieee", "gtech"].toHashSet,
"ramlib": ["std", "ieee"].toHashSet,
"std_cell_lib": ["ieee", "std_cell_lib"].toHashSet,
"synopsys": initHashSet[string]()}.toOrderedTable
echo "Data without cycle. Order after sorting:"
var data = Data
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
echo "\nData with a cycle:"
data = Data
data["dw01"].incl "dw04"
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Convert the following code from Nim to Go, ensuring the logic remains intact. | import sequtils, strutils, sets, tables, sugar
type StringSet = HashSet[string]
proc topSort(data: var OrderedTable[string, StringSet]) =
var ranks: Table[string, Natural]
for key, values in data.mpairs:
values.excl key
for values in toSeq(data.values):
for value in values:
if value notin data:
data[value] = initHashSet[string]()
var deps = data
var rank = 0
while deps.len > 0:
var keyToRemove: string
for key, values in deps.pairs:
if values.card == 0:
keyToRemove = key
break
if keyToRemove.len == 0:
raise newException(ValueError, "Unorderable items found: " & toSeq(deps.keys).join(", "))
ranks[keyToRemove] = rank
inc rank
deps.del keyToRemove
for k, v in deps.mpairs:
v.excl keyToRemove
data.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))
when isMainModule:
const Data = {"des_system_lib": ["std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01",
"ramlib", "ieee"].toHashSet,
"dw01": ["ieee", "dw01", "dware", "gtech"].toHashSet,
"dw02": ["ieee", "dw02", "dware"].toHashSet,
"dw03": ["std", "synopsys", "dware", "dw03",
"dw02", "dw01", "ieee", "gtech"].toHashSet,
"dw04": ["dw04", "ieee", "dw01", "dware", "gtech"].toHashSet,
"dw05": ["dw05", "ieee", "dware"].toHashSet,
"dw06": ["dw06", "ieee", "dware"].toHashSet,
"dw07": ["ieee", "dware"].toHashSet,
"dware": ["ieee", "dware"].toHashSet,
"gtech": ["ieee", "gtech"].toHashSet,
"ramlib": ["std", "ieee"].toHashSet,
"std_cell_lib": ["ieee", "std_cell_lib"].toHashSet,
"synopsys": initHashSet[string]()}.toOrderedTable
echo "Data without cycle. Order after sorting:"
var data = Data
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
echo "\nData with a cycle:"
data = Data
data["dw01"].incl "dw04"
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Generate an equivalent C version of this OCaml code. | let dep_libs = [
("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", []);
]
let dep_libs =
let f (lib, deps) =
(lib,
List.filter (fun d -> d <> lib) deps) in
List.map f dep_libs
let rev_unique =
List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []
let libs =
rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))
let get_deps lib =
try (List.assoc lib dep_libs)
with Not_found -> []
let res =
let rec aux acc later todo progress =
match todo, later with
| [], [] -> (List.rev acc)
| [], _ ->
if progress
then aux acc [] later false
else invalid_arg "un-orderable data"
| x::xs, _ ->
let deps = get_deps x in
let ok = List.for_all (fun dep -> List.mem dep acc) deps in
if ok
then aux (x::acc) later xs true
else aux acc (x::later) xs progress
in
let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
aux starts [] todo false
let () =
print_string "result: \n ";
print_endline (String.concat ", " res);
;;
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char input[] =
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, "\n", &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, " \t", &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf("Compile order:\n");
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf(" [unorderable]");
else printf("%d:", i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(" %s", items[j].name);
}
return 0;
}
|
Translate this program into C# but keep the logic exactly as in OCaml. | let dep_libs = [
("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", []);
]
let dep_libs =
let f (lib, deps) =
(lib,
List.filter (fun d -> d <> lib) deps) in
List.map f dep_libs
let rev_unique =
List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []
let libs =
rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))
let get_deps lib =
try (List.assoc lib dep_libs)
with Not_found -> []
let res =
let rec aux acc later todo progress =
match todo, later with
| [], [] -> (List.rev acc)
| [], _ ->
if progress
then aux acc [] later false
else invalid_arg "un-orderable data"
| x::xs, _ ->
let deps = get_deps x in
let ok = List.for_all (fun dep -> List.mem dep acc) deps in
if ok
then aux (x::acc) later xs true
else aux acc (x::later) xs progress
in
let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
aux starts [] todo false
let () =
print_string "result: \n ";
print_endline (String.concat ", " res);
;;
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Rewrite the snippet below in C++ so it works the same as the original OCaml code. | let dep_libs = [
("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", []);
]
let dep_libs =
let f (lib, deps) =
(lib,
List.filter (fun d -> d <> lib) deps) in
List.map f dep_libs
let rev_unique =
List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []
let libs =
rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))
let get_deps lib =
try (List.assoc lib dep_libs)
with Not_found -> []
let res =
let rec aux acc later todo progress =
match todo, later with
| [], [] -> (List.rev acc)
| [], _ ->
if progress
then aux acc [] later false
else invalid_arg "un-orderable data"
| x::xs, _ ->
let deps = get_deps x in
let ok = List.for_all (fun dep -> List.mem dep acc) deps in
if ok
then aux (x::acc) later xs true
else aux acc (x::later) xs progress
in
let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
aux starts [] todo false
let () =
print_string "result: \n ";
print_endline (String.concat ", " res);
;;
| #include <map>
#include <set>
template<typename Goal>
class topological_sorter {
protected:
struct relations {
std::size_t dependencies;
std::set<Goal> dependents;
};
std::map<Goal, relations> map;
public:
void add_goal(Goal const &goal) {
map[goal];
}
void add_dependency(Goal const &goal, Goal const &dependency) {
if (dependency == goal)
return;
auto &dependents = map[dependency].dependents;
if (dependents.find(goal) == dependents.end()) {
dependents.insert(goal);
++map[goal].dependencies;
}
}
template<typename Container>
void add_dependencies(Goal const &goal, Container const &dependencies) {
for (auto const &dependency : dependencies)
add_dependency(goal, dependency);
}
template<typename ResultContainer, typename CyclicContainer>
void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
sorted.clear();
unsortable.clear();
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies == 0)
sorted.push_back(goal);
}
for (std::size_t index = 0; index < sorted.size(); ++index)
for (auto const &goal : map[sorted[index]].dependents)
if (--map[goal].dependencies == 0)
sorted.push_back(goal);
for (auto const &lookup : map) {
auto const &goal = lookup.first;
auto const &relations = lookup.second;
if (relations.dependencies != 0)
unsortable.push_back(goal);
}
}
template<typename ResultContainer, typename CyclicContainer>
void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
topological_sorter<Goal> temporary = *this;
temporary.destructive_sort(sorted, unsortable);
}
void clear() {
map.clear();
}
};
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void display_heading(string const &message) {
cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
topological_sorter<string> sorter;
vector<string> sorted, unsortable;
stringstream lines(input);
string line;
while (getline(lines, line)) {
stringstream buffer(line);
string goal, dependency;
buffer >> goal;
sorter.add_goal(goal);
while (buffer >> dependency)
sorter.add_dependency(goal, dependency);
}
sorter.destructive_sort(sorted, unsortable);
if (sorted.size() == 0)
display_heading("Error: no independent variables found!");
else {
display_heading("Result");
for (auto const &goal : sorted)
cout << goal << endl;
}
if (unsortable.size() != 0) {
display_heading("Error: cyclic dependencies detected!");
for (auto const &goal : unsortable)
cout << goal << endl;
}
}
int main(int argc, char **argv) {
if (argc == 1) {
string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
"dw01 ieee dw01 dware gtech\n"
"dw02 ieee dw02 dware\n"
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n"
"dw04 dw04 ieee dw01 dware gtech\n"
"dw05 dw05 ieee dware\n"
"dw06 dw06 ieee dware\n"
"dw07 ieee dware\n"
"dware ieee dware\n"
"gtech ieee gtech\n"
"ramlib std ieee\n"
"std_cell_lib ieee std_cell_lib\n"
"synopsys\n"
"cycle_11 cycle_12\n"
"cycle_12 cycle_11\n"
"cycle_21 dw01 cycle_22 dw02 dw03\n"
"cycle_22 cycle_21 dw01 dw04";
display_heading("Example: each line starts with a goal followed by it's dependencies");
cout << example << endl;
display_results(example);
display_heading("Enter lines of data (press enter when finished)");
string line, data;
while (getline(cin, line) && !line.empty())
data += line + '\n';
if (!data.empty())
display_results(data);
} else
while (*(++argv)) {
ifstream file(*argv);
typedef istreambuf_iterator<char> iterator;
display_results(string(iterator(file), iterator()));
}
}
|
Translate the given OCaml code snippet into Java without altering its behavior. | let dep_libs = [
("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", []);
]
let dep_libs =
let f (lib, deps) =
(lib,
List.filter (fun d -> d <> lib) deps) in
List.map f dep_libs
let rev_unique =
List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []
let libs =
rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))
let get_deps lib =
try (List.assoc lib dep_libs)
with Not_found -> []
let res =
let rec aux acc later todo progress =
match todo, later with
| [], [] -> (List.rev acc)
| [], _ ->
if progress
then aux acc [] later false
else invalid_arg "un-orderable data"
| x::xs, _ ->
let deps = get_deps x in
let ok = List.for_all (fun dep -> List.mem dep acc) deps in
if ok
then aux (x::acc) later xs true
else aux acc (x::later) xs progress
in
let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
aux starts [] todo false
let () =
print_string "result: \n ";
print_endline (String.concat ", " res);
;;
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Convert this OCaml snippet to Python and keep its semantics consistent. | let dep_libs = [
("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", []);
]
let dep_libs =
let f (lib, deps) =
(lib,
List.filter (fun d -> d <> lib) deps) in
List.map f dep_libs
let rev_unique =
List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []
let libs =
rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))
let get_deps lib =
try (List.assoc lib dep_libs)
with Not_found -> []
let res =
let rec aux acc later todo progress =
match todo, later with
| [], [] -> (List.rev acc)
| [], _ ->
if progress
then aux acc [] later false
else invalid_arg "un-orderable data"
| x::xs, _ ->
let deps = get_deps x in
let ok = List.for_all (fun dep -> List.mem dep acc) deps in
if ok
then aux (x::acc) later xs true
else aux acc (x::later) xs progress
in
let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
aux starts [] todo false
let () =
print_string "result: \n ";
print_endline (String.concat ", " res);
;;
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Produce a functionally identical VB code for the snippet given in OCaml. | let dep_libs = [
("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", []);
]
let dep_libs =
let f (lib, deps) =
(lib,
List.filter (fun d -> d <> lib) deps) in
List.map f dep_libs
let rev_unique =
List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []
let libs =
rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))
let get_deps lib =
try (List.assoc lib dep_libs)
with Not_found -> []
let res =
let rec aux acc later todo progress =
match todo, later with
| [], [] -> (List.rev acc)
| [], _ ->
if progress
then aux acc [] later false
else invalid_arg "un-orderable data"
| x::xs, _ ->
let deps = get_deps x in
let ok = List.for_all (fun dep -> List.mem dep acc) deps in
if ok
then aux (x::acc) later xs true
else aux acc (x::later) xs progress
in
let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
aux starts [] todo false
let () =
print_string "result: \n ";
print_endline (String.concat ", " res);
;;
| class topological
dim dictDependencies
dim dictReported
dim depth
sub class_initialize
set dictDependencies = createobject("Scripting.Dictionary")
set dictReported = createobject("Scripting.Dictionary")
depth = 0
end sub
sub reset
dictReported.removeall
end sub
property let dependencies( s )
dim i, j ,k
dim aList
dim dep
dim a1
aList = Split( s, vbNewLine )
do while aList( UBound( aList ) ) = vbnullstring
redim preserve aList( UBound( aList ) - 1 )
loop
for i = lbound( aList ) to ubound( aList )
aList( i ) = Split( aList( i ), vbTab, 2 )
a1 = Split( aList( i )( 1 ), " " )
k = 0
for j = lbound( a1) to ubound(a1)
if a1(j) <> aList(i)(0) then
a1(k) = a1(j)
k = k + 1
end if
next
redim preserve a1(k-1)
aList(i)(1) = a1
next
for i = lbound( aList ) to ubound( aList )
dep = aList(i)(0)
if not dictDependencies.Exists( dep ) then
dictDependencies.add dep, aList(i)(1)
end if
next
end property
sub resolve( s )
dim i
dim deps
depth = depth + 1
if dictDependencies.Exists(s) then
deps = dictDependencies(s)
for i = lbound(deps) to ubound(deps)
resolve deps(i)
next
end if
if not seen(s) then
wscript.echo s
see s
end if
depth = depth - 1
end sub
function seen( key )
seen = dictReported.Exists( key )
end function
sub see( key )
dictReported.add key, ""
end sub
property get keys
keys = dictDependencies.keys
end property
end class
|
Port the following code from OCaml to Go with equivalent syntax and logic. | let dep_libs = [
("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", []);
]
let dep_libs =
let f (lib, deps) =
(lib,
List.filter (fun d -> d <> lib) deps) in
List.map f dep_libs
let rev_unique =
List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []
let libs =
rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))
let get_deps lib =
try (List.assoc lib dep_libs)
with Not_found -> []
let res =
let rec aux acc later todo progress =
match todo, later with
| [], [] -> (List.rev acc)
| [], _ ->
if progress
then aux acc [] later false
else invalid_arg "un-orderable data"
| x::xs, _ ->
let deps = get_deps x in
let ok = List.for_all (fun dep -> List.mem dep acc) deps in
if ok
then aux (x::acc) later xs true
else aux acc (x::later) xs progress
in
let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
aux starts [] todo false
let () =
print_string "result: \n ";
print_endline (String.concat ", " res);
;;
| package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
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 `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int
func parseLibComp(data string) (g graph, in inDegree, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
in = inDegree{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
g[lib] = g[lib]
for _, dep := range libs[1:] {
in[dep] = in[dep]
if dep == lib {
continue
}
successors := g[dep]
for i := 0; ; i++ {
if i == len(successors) {
g[dep] = append(successors, lib)
in[lib]++
break
}
if dep == successors[i] {
break
}
}
}
}
return g, in, nil
}
func topSortKahn(g graph, in inDegree) (order, cyclic []string) {
var L, S []string
rem := inDegree{}
for n, d := range in {
if d == 0 {
S = append(S, n)
} else {
rem[n] = d
}
}
for len(S) > 0 {
last := len(S) - 1
n := S[last]
S = S[:last]
L = append(L, n)
for _, m := range g[n] {
if rem[m] > 0 {
rem[m]--
if rem[m] == 0 {
S = append(S, m)
}
}
}
}
for c, in := range rem {
if in > 0 {
for _, nb := range g[c] {
if rem[nb] > 0 {
cyclic = append(cyclic, c)
break
}
}
}
}
if len(cyclic) > 0 {
return nil, cyclic
}
return L, nil
}
|
Write the same code in C# as shown below in Pascal. | program topologicalsortrosetta;
uses
cwstring,
cthreads,
Classes,
SysUtils;
type
RNodeIndex = record
NodeName: WideString;
Order: integer;
end;
RDepGraph = record
Node: integer;
DependsOn: integer;
end;
TTopologicalSort = class(TObject)
private
Nodes: array of RNodeIndex;
DependencyGraph: array of RDepGraph;
FCanBeSorted: boolean;
function SearchNode(NodeName: WideString): integer;
function SearchIndex(NodeID: integer): WideString;
function DepFromNodeID(NodeID: integer): integer;
function DepFromDepID(DepID: integer): integer;
function DepFromNodeIDDepID(NodeID, DepID: integer): integer;
procedure DelDependency(const Index: integer);
public
constructor Create;
destructor Destroy; override;
procedure SortOrder(var Output: TStringList);
procedure AddNode(NodeName: WideString);
procedure AddDependency(NodeName, DependsOn: WideString);
procedure AddNodeDependencies(NodeAndDependencies: TStringList);
procedure DelDependency(NodeName, DependsOn: WideString);
property CanBeSorted: boolean read FCanBeSorted;
end;
const
INVALID = -1;
function TTopologicalSort.SearchNode(NodeName: WideString): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(Nodes) do
begin
if Nodes[Counter].NodeName = NodeName then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.SearchIndex(NodeID: integer): WideString;
begin
if (NodeID > 0) and (NodeID <= High(Nodes)) then
begin
Result := Nodes[NodeID].NodeName;
end
else
begin
Result := 'ERROR';
end;
end;
function TTopologicalSort.DepFromNodeID(NodeID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].Node = NodeID then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.DepFromDepID(DepID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].DependsOn = DepID then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.DepFromNodeIDDepID(NodeID, DepID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].Node = NodeID then
if DependencyGraph[Counter].DependsOn = DepID then
begin
Result := Counter;
break;
end;
end;
end;
procedure TTopologicalSort.DelDependency(const Index: integer);
var
Counter: integer;
OriginalLength: integer;
begin
OriginalLength := Length(DependencyGraph);
if Index = OriginalLength - 1 then
begin
SetLength(DependencyGraph, OriginalLength - 1);
end;
if Index < OriginalLength - 1 then
begin
for Counter := Index to OriginalLength - 2 do
begin
DependencyGraph[Counter] := DependencyGraph[Counter + 1];
end;
SetLength(DependencyGraph, OriginalLength - 1);
end;
if Index > OriginalLength - 1 then
begin
raise Exception.Create('Tried to delete index ' + IntToStr(Index) +
' while the maximum index was ' + IntToStr(OriginalLength - 1));
end;
end;
constructor TTopologicalSort.Create;
begin
inherited Create;
end;
destructor TTopologicalSort.Destroy;
begin
Finalize(DependencyGraph);
Finalize(Nodes);
inherited;
end;
procedure TTopologicalSort.SortOrder(var Output: TStringList);
var
Counter: integer;
NodeCounter: integer;
OutputSortOrder: integer;
DidSomething: boolean;
Node: integer;
begin
OutputSortOrder := 0;
DidSomething := True;
FCanBeSorted := True;
while (DidSomething = True) do
begin
for Counter := 0 to High(Nodes) do
begin
if DepFromNodeID(Counter) = INVALID then
begin
if DepFromDepID(Counter) = INVALID then
begin
DidSomething := True;
if (Nodes[Counter].Order = INVALID) or
(Nodes[Counter].Order > OutputSortOrder) then
begin
Nodes[Counter].Order := OutputSortOrder;
end;
end;
end;
end;
OutputSortOrder := OutputSortOrder + 1;
DidSomething := False;
for Counter := High(DependencyGraph) downto 0 do
begin
Node := DependencyGraph[Counter].DependsOn;
if (DepFromNodeID(Node) = INVALID) then
begin
DidSomething := True;
DelDependency(Counter);
if (Nodes[Node].Order = INVALID) or (Nodes[Node].Order > OutputSortOrder) then
begin
Nodes[Node].Order := OutputSortOrder;
end;
end;
OutputSortOrder := OutputSortOrder + 1;
end;
OutputSortOrder := OutputSortOrder + 1;
end;
OutputSortOrder := OutputSortOrder - 1;
if (High(DependencyGraph) > 0) then
begin
FCanBeSorted := False;
Output.Add('Cycle (circular dependency) detected, cannot sort further. Dependencies left:');
for Counter := 0 to High(DependencyGraph) do
begin
Output.Add(SearchIndex(DependencyGraph[Counter].Node) +
' depends on: ' + SearchIndex(DependencyGraph[Counter].DependsOn));
end;
end
else
begin
for Counter := 0 to OutputSortOrder do
begin
for NodeCounter := 0 to High(Nodes) do
begin
if Nodes[NodeCounter].Order = Counter then
begin
Output.Add(Nodes[NodeCounter].NodeName);
end;
end;
end;
end;
end;
procedure TTopologicalSort.AddNode(NodeName: WideString);
var
NodesNewLength: integer;
begin
if SearchNode(NodeName) = INVALID then
begin
NodesNewLength := Length(Nodes) + 1;
SetLength(Nodes, NodesNewLength);
Nodes[NodesNewLength - 1].NodeName := NodeName;
Nodes[NodesNewLength - 1].Order := INVALID;
end;
end;
procedure TTopologicalSort.AddDependency(NodeName, DependsOn: WideString);
begin
if SearchNode(NodeName) = INVALID then
begin
Self.AddNode(NodeName);
end;
if SearchNode(DependsOn) = INVALID then
begin
Self.AddNode(DependsOn);
end;
if NodeName <> DependsOn then
begin
SetLength(DependencyGraph, Length(DependencyGraph) + 1);
DependencyGraph[High(DependencyGraph)].Node := SearchNode(NodeName);
DependencyGraph[High(DependencyGraph)].DependsOn := SearchNode(DependsOn);
end;
end;
procedure TTopologicalSort.AddNodeDependencies(NodeAndDependencies: TStringList);
var
Deplist: TStringList;
StringCounter: integer;
NodeCounter: integer;
begin
if Assigned(NodeAndDependencies) then
begin
DepList := TStringList.Create;
try
for StringCounter := 0 to NodeAndDependencies.Count - 1 do
begin
DepList.Delimiter := ' ';
DepList.StrictDelimiter := False;
DepList.DelimitedText := NodeAndDependencies[StringCounter];
for NodeCounter := 0 to DepList.Count - 1 do
begin
if NodeCounter = 0 then
begin
Self.AddNode(Deplist[0]);
end;
if NodeCounter > 0 then
begin
Self.AddDependency(DepList[0], DepList[NodeCounter]);
end;
end;
end;
finally
DepList.Free;
end;
end;
end;
procedure TTopologicalSort.DelDependency(NodeName, DependsOn: WideString);
var
NodeID: integer;
DependsID: integer;
Dependency: integer;
begin
NodeID := Self.SearchNode(NodeName);
DependsID := Self.SearchNode(DependsOn);
if (NodeID <> INVALID) and (DependsID <> INVALID) then
begin
Dependency := Self.DepFromNodeIDDepID(NodeID, DependsID);
if (Dependency <> INVALID) then
begin
Self.DelDependency(Dependency);
end;
end;
end;
var
InputList: TStringList;
TopSort: TTopologicalSort;
OutputList: TStringList;
Counter: integer;
begin
InputList := TStringList.Create;
InputList.Add(
'des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee');
InputList.Add('dw01 ieee dw01 dware gtech');
InputList.Add('dw02 ieee dw02 dware');
InputList.Add('dw03 std synopsys dware dw03 dw02 dw01 ieee gtech');
InputList.Add('dw04 dw04 ieee dw01 dware gtech');
InputList.Add('dw05 dw05 ieee dware');
InputList.Add('dw06 dw06 ieee dware');
InputList.Add('dw07 ieee dware');
InputList.Add('dware ieee dware');
InputList.Add('gtech ieee gtech');
InputList.Add('ramlib std ieee');
InputList.Add('std_cell_lib ieee std_cell_lib');
InputList.Add('synopsys');
TopSort := TTopologicalSort.Create;
OutputList := TStringList.Create;
try
TopSort.AddNodeDependencies(InputList);
TopSort.SortOrder(OutputList);
for Counter := 0 to OutputList.Count - 1 do
begin
writeln(OutputList[Counter]);
end;
except
on E: Exception do
begin
Writeln(stderr, 'Error: ', DateTimeToStr(Now),
': Error sorting. Technical details: ',
E.ClassName, '/', E.Message);
end;
end;
OutputList.Free;
TopSort.Free;
InputList.Free;
end.
| 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();
}
}
}
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" },
new Task{ Message = "B - depends on none" },
new Task{ Message = "C - depends on D and E" },
new Task{ Message = "D - depends on none" },
new Task{ Message = "E - depends on F, G and H" },
new Task{ Message = "F - depends on I" },
new Task{ Message = "G - depends on none" },
new Task{ Message = "H - depends on none" },
new Task{ Message = "I - depends on none" },
};
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
resolver.Add(tasks[5], tasks[8]);
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...");
}
}
}
|
Produce a language-to-language conversion: from Pascal to Java, same semantics. | program topologicalsortrosetta;
uses
cwstring,
cthreads,
Classes,
SysUtils;
type
RNodeIndex = record
NodeName: WideString;
Order: integer;
end;
RDepGraph = record
Node: integer;
DependsOn: integer;
end;
TTopologicalSort = class(TObject)
private
Nodes: array of RNodeIndex;
DependencyGraph: array of RDepGraph;
FCanBeSorted: boolean;
function SearchNode(NodeName: WideString): integer;
function SearchIndex(NodeID: integer): WideString;
function DepFromNodeID(NodeID: integer): integer;
function DepFromDepID(DepID: integer): integer;
function DepFromNodeIDDepID(NodeID, DepID: integer): integer;
procedure DelDependency(const Index: integer);
public
constructor Create;
destructor Destroy; override;
procedure SortOrder(var Output: TStringList);
procedure AddNode(NodeName: WideString);
procedure AddDependency(NodeName, DependsOn: WideString);
procedure AddNodeDependencies(NodeAndDependencies: TStringList);
procedure DelDependency(NodeName, DependsOn: WideString);
property CanBeSorted: boolean read FCanBeSorted;
end;
const
INVALID = -1;
function TTopologicalSort.SearchNode(NodeName: WideString): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(Nodes) do
begin
if Nodes[Counter].NodeName = NodeName then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.SearchIndex(NodeID: integer): WideString;
begin
if (NodeID > 0) and (NodeID <= High(Nodes)) then
begin
Result := Nodes[NodeID].NodeName;
end
else
begin
Result := 'ERROR';
end;
end;
function TTopologicalSort.DepFromNodeID(NodeID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].Node = NodeID then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.DepFromDepID(DepID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].DependsOn = DepID then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.DepFromNodeIDDepID(NodeID, DepID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].Node = NodeID then
if DependencyGraph[Counter].DependsOn = DepID then
begin
Result := Counter;
break;
end;
end;
end;
procedure TTopologicalSort.DelDependency(const Index: integer);
var
Counter: integer;
OriginalLength: integer;
begin
OriginalLength := Length(DependencyGraph);
if Index = OriginalLength - 1 then
begin
SetLength(DependencyGraph, OriginalLength - 1);
end;
if Index < OriginalLength - 1 then
begin
for Counter := Index to OriginalLength - 2 do
begin
DependencyGraph[Counter] := DependencyGraph[Counter + 1];
end;
SetLength(DependencyGraph, OriginalLength - 1);
end;
if Index > OriginalLength - 1 then
begin
raise Exception.Create('Tried to delete index ' + IntToStr(Index) +
' while the maximum index was ' + IntToStr(OriginalLength - 1));
end;
end;
constructor TTopologicalSort.Create;
begin
inherited Create;
end;
destructor TTopologicalSort.Destroy;
begin
Finalize(DependencyGraph);
Finalize(Nodes);
inherited;
end;
procedure TTopologicalSort.SortOrder(var Output: TStringList);
var
Counter: integer;
NodeCounter: integer;
OutputSortOrder: integer;
DidSomething: boolean;
Node: integer;
begin
OutputSortOrder := 0;
DidSomething := True;
FCanBeSorted := True;
while (DidSomething = True) do
begin
for Counter := 0 to High(Nodes) do
begin
if DepFromNodeID(Counter) = INVALID then
begin
if DepFromDepID(Counter) = INVALID then
begin
DidSomething := True;
if (Nodes[Counter].Order = INVALID) or
(Nodes[Counter].Order > OutputSortOrder) then
begin
Nodes[Counter].Order := OutputSortOrder;
end;
end;
end;
end;
OutputSortOrder := OutputSortOrder + 1;
DidSomething := False;
for Counter := High(DependencyGraph) downto 0 do
begin
Node := DependencyGraph[Counter].DependsOn;
if (DepFromNodeID(Node) = INVALID) then
begin
DidSomething := True;
DelDependency(Counter);
if (Nodes[Node].Order = INVALID) or (Nodes[Node].Order > OutputSortOrder) then
begin
Nodes[Node].Order := OutputSortOrder;
end;
end;
OutputSortOrder := OutputSortOrder + 1;
end;
OutputSortOrder := OutputSortOrder + 1;
end;
OutputSortOrder := OutputSortOrder - 1;
if (High(DependencyGraph) > 0) then
begin
FCanBeSorted := False;
Output.Add('Cycle (circular dependency) detected, cannot sort further. Dependencies left:');
for Counter := 0 to High(DependencyGraph) do
begin
Output.Add(SearchIndex(DependencyGraph[Counter].Node) +
' depends on: ' + SearchIndex(DependencyGraph[Counter].DependsOn));
end;
end
else
begin
for Counter := 0 to OutputSortOrder do
begin
for NodeCounter := 0 to High(Nodes) do
begin
if Nodes[NodeCounter].Order = Counter then
begin
Output.Add(Nodes[NodeCounter].NodeName);
end;
end;
end;
end;
end;
procedure TTopologicalSort.AddNode(NodeName: WideString);
var
NodesNewLength: integer;
begin
if SearchNode(NodeName) = INVALID then
begin
NodesNewLength := Length(Nodes) + 1;
SetLength(Nodes, NodesNewLength);
Nodes[NodesNewLength - 1].NodeName := NodeName;
Nodes[NodesNewLength - 1].Order := INVALID;
end;
end;
procedure TTopologicalSort.AddDependency(NodeName, DependsOn: WideString);
begin
if SearchNode(NodeName) = INVALID then
begin
Self.AddNode(NodeName);
end;
if SearchNode(DependsOn) = INVALID then
begin
Self.AddNode(DependsOn);
end;
if NodeName <> DependsOn then
begin
SetLength(DependencyGraph, Length(DependencyGraph) + 1);
DependencyGraph[High(DependencyGraph)].Node := SearchNode(NodeName);
DependencyGraph[High(DependencyGraph)].DependsOn := SearchNode(DependsOn);
end;
end;
procedure TTopologicalSort.AddNodeDependencies(NodeAndDependencies: TStringList);
var
Deplist: TStringList;
StringCounter: integer;
NodeCounter: integer;
begin
if Assigned(NodeAndDependencies) then
begin
DepList := TStringList.Create;
try
for StringCounter := 0 to NodeAndDependencies.Count - 1 do
begin
DepList.Delimiter := ' ';
DepList.StrictDelimiter := False;
DepList.DelimitedText := NodeAndDependencies[StringCounter];
for NodeCounter := 0 to DepList.Count - 1 do
begin
if NodeCounter = 0 then
begin
Self.AddNode(Deplist[0]);
end;
if NodeCounter > 0 then
begin
Self.AddDependency(DepList[0], DepList[NodeCounter]);
end;
end;
end;
finally
DepList.Free;
end;
end;
end;
procedure TTopologicalSort.DelDependency(NodeName, DependsOn: WideString);
var
NodeID: integer;
DependsID: integer;
Dependency: integer;
begin
NodeID := Self.SearchNode(NodeName);
DependsID := Self.SearchNode(DependsOn);
if (NodeID <> INVALID) and (DependsID <> INVALID) then
begin
Dependency := Self.DepFromNodeIDDepID(NodeID, DependsID);
if (Dependency <> INVALID) then
begin
Self.DelDependency(Dependency);
end;
end;
end;
var
InputList: TStringList;
TopSort: TTopologicalSort;
OutputList: TStringList;
Counter: integer;
begin
InputList := TStringList.Create;
InputList.Add(
'des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee');
InputList.Add('dw01 ieee dw01 dware gtech');
InputList.Add('dw02 ieee dw02 dware');
InputList.Add('dw03 std synopsys dware dw03 dw02 dw01 ieee gtech');
InputList.Add('dw04 dw04 ieee dw01 dware gtech');
InputList.Add('dw05 dw05 ieee dware');
InputList.Add('dw06 dw06 ieee dware');
InputList.Add('dw07 ieee dware');
InputList.Add('dware ieee dware');
InputList.Add('gtech ieee gtech');
InputList.Add('ramlib std ieee');
InputList.Add('std_cell_lib ieee std_cell_lib');
InputList.Add('synopsys');
TopSort := TTopologicalSort.Create;
OutputList := TStringList.Create;
try
TopSort.AddNodeDependencies(InputList);
TopSort.SortOrder(OutputList);
for Counter := 0 to OutputList.Count - 1 do
begin
writeln(OutputList[Counter]);
end;
except
on E: Exception do
begin
Writeln(stderr, 'Error: ', DateTimeToStr(Now),
': Error sorting. Technical details: ',
E.ClassName, '/', E.Message);
end;
end;
OutputList.Free;
TopSort.Free;
InputList.Free;
end.
| import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]);
continue outer;
}
}
throw new Exception("Graph has cycles");
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return result;
}
boolean hasDependency(Integer r, List<Integer> todo) {
for (Integer c : todo) {
if (adjacency[r][c])
return true;
}
return false;
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | program topologicalsortrosetta;
uses
cwstring,
cthreads,
Classes,
SysUtils;
type
RNodeIndex = record
NodeName: WideString;
Order: integer;
end;
RDepGraph = record
Node: integer;
DependsOn: integer;
end;
TTopologicalSort = class(TObject)
private
Nodes: array of RNodeIndex;
DependencyGraph: array of RDepGraph;
FCanBeSorted: boolean;
function SearchNode(NodeName: WideString): integer;
function SearchIndex(NodeID: integer): WideString;
function DepFromNodeID(NodeID: integer): integer;
function DepFromDepID(DepID: integer): integer;
function DepFromNodeIDDepID(NodeID, DepID: integer): integer;
procedure DelDependency(const Index: integer);
public
constructor Create;
destructor Destroy; override;
procedure SortOrder(var Output: TStringList);
procedure AddNode(NodeName: WideString);
procedure AddDependency(NodeName, DependsOn: WideString);
procedure AddNodeDependencies(NodeAndDependencies: TStringList);
procedure DelDependency(NodeName, DependsOn: WideString);
property CanBeSorted: boolean read FCanBeSorted;
end;
const
INVALID = -1;
function TTopologicalSort.SearchNode(NodeName: WideString): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(Nodes) do
begin
if Nodes[Counter].NodeName = NodeName then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.SearchIndex(NodeID: integer): WideString;
begin
if (NodeID > 0) and (NodeID <= High(Nodes)) then
begin
Result := Nodes[NodeID].NodeName;
end
else
begin
Result := 'ERROR';
end;
end;
function TTopologicalSort.DepFromNodeID(NodeID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].Node = NodeID then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.DepFromDepID(DepID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].DependsOn = DepID then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.DepFromNodeIDDepID(NodeID, DepID: integer): integer;
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].Node = NodeID then
if DependencyGraph[Counter].DependsOn = DepID then
begin
Result := Counter;
break;
end;
end;
end;
procedure TTopologicalSort.DelDependency(const Index: integer);
var
Counter: integer;
OriginalLength: integer;
begin
OriginalLength := Length(DependencyGraph);
if Index = OriginalLength - 1 then
begin
SetLength(DependencyGraph, OriginalLength - 1);
end;
if Index < OriginalLength - 1 then
begin
for Counter := Index to OriginalLength - 2 do
begin
DependencyGraph[Counter] := DependencyGraph[Counter + 1];
end;
SetLength(DependencyGraph, OriginalLength - 1);
end;
if Index > OriginalLength - 1 then
begin
raise Exception.Create('Tried to delete index ' + IntToStr(Index) +
' while the maximum index was ' + IntToStr(OriginalLength - 1));
end;
end;
constructor TTopologicalSort.Create;
begin
inherited Create;
end;
destructor TTopologicalSort.Destroy;
begin
Finalize(DependencyGraph);
Finalize(Nodes);
inherited;
end;
procedure TTopologicalSort.SortOrder(var Output: TStringList);
var
Counter: integer;
NodeCounter: integer;
OutputSortOrder: integer;
DidSomething: boolean;
Node: integer;
begin
OutputSortOrder := 0;
DidSomething := True;
FCanBeSorted := True;
while (DidSomething = True) do
begin
for Counter := 0 to High(Nodes) do
begin
if DepFromNodeID(Counter) = INVALID then
begin
if DepFromDepID(Counter) = INVALID then
begin
DidSomething := True;
if (Nodes[Counter].Order = INVALID) or
(Nodes[Counter].Order > OutputSortOrder) then
begin
Nodes[Counter].Order := OutputSortOrder;
end;
end;
end;
end;
OutputSortOrder := OutputSortOrder + 1;
DidSomething := False;
for Counter := High(DependencyGraph) downto 0 do
begin
Node := DependencyGraph[Counter].DependsOn;
if (DepFromNodeID(Node) = INVALID) then
begin
DidSomething := True;
DelDependency(Counter);
if (Nodes[Node].Order = INVALID) or (Nodes[Node].Order > OutputSortOrder) then
begin
Nodes[Node].Order := OutputSortOrder;
end;
end;
OutputSortOrder := OutputSortOrder + 1;
end;
OutputSortOrder := OutputSortOrder + 1;
end;
OutputSortOrder := OutputSortOrder - 1;
if (High(DependencyGraph) > 0) then
begin
FCanBeSorted := False;
Output.Add('Cycle (circular dependency) detected, cannot sort further. Dependencies left:');
for Counter := 0 to High(DependencyGraph) do
begin
Output.Add(SearchIndex(DependencyGraph[Counter].Node) +
' depends on: ' + SearchIndex(DependencyGraph[Counter].DependsOn));
end;
end
else
begin
for Counter := 0 to OutputSortOrder do
begin
for NodeCounter := 0 to High(Nodes) do
begin
if Nodes[NodeCounter].Order = Counter then
begin
Output.Add(Nodes[NodeCounter].NodeName);
end;
end;
end;
end;
end;
procedure TTopologicalSort.AddNode(NodeName: WideString);
var
NodesNewLength: integer;
begin
if SearchNode(NodeName) = INVALID then
begin
NodesNewLength := Length(Nodes) + 1;
SetLength(Nodes, NodesNewLength);
Nodes[NodesNewLength - 1].NodeName := NodeName;
Nodes[NodesNewLength - 1].Order := INVALID;
end;
end;
procedure TTopologicalSort.AddDependency(NodeName, DependsOn: WideString);
begin
if SearchNode(NodeName) = INVALID then
begin
Self.AddNode(NodeName);
end;
if SearchNode(DependsOn) = INVALID then
begin
Self.AddNode(DependsOn);
end;
if NodeName <> DependsOn then
begin
SetLength(DependencyGraph, Length(DependencyGraph) + 1);
DependencyGraph[High(DependencyGraph)].Node := SearchNode(NodeName);
DependencyGraph[High(DependencyGraph)].DependsOn := SearchNode(DependsOn);
end;
end;
procedure TTopologicalSort.AddNodeDependencies(NodeAndDependencies: TStringList);
var
Deplist: TStringList;
StringCounter: integer;
NodeCounter: integer;
begin
if Assigned(NodeAndDependencies) then
begin
DepList := TStringList.Create;
try
for StringCounter := 0 to NodeAndDependencies.Count - 1 do
begin
DepList.Delimiter := ' ';
DepList.StrictDelimiter := False;
DepList.DelimitedText := NodeAndDependencies[StringCounter];
for NodeCounter := 0 to DepList.Count - 1 do
begin
if NodeCounter = 0 then
begin
Self.AddNode(Deplist[0]);
end;
if NodeCounter > 0 then
begin
Self.AddDependency(DepList[0], DepList[NodeCounter]);
end;
end;
end;
finally
DepList.Free;
end;
end;
end;
procedure TTopologicalSort.DelDependency(NodeName, DependsOn: WideString);
var
NodeID: integer;
DependsID: integer;
Dependency: integer;
begin
NodeID := Self.SearchNode(NodeName);
DependsID := Self.SearchNode(DependsOn);
if (NodeID <> INVALID) and (DependsID <> INVALID) then
begin
Dependency := Self.DepFromNodeIDDepID(NodeID, DependsID);
if (Dependency <> INVALID) then
begin
Self.DelDependency(Dependency);
end;
end;
end;
var
InputList: TStringList;
TopSort: TTopologicalSort;
OutputList: TStringList;
Counter: integer;
begin
InputList := TStringList.Create;
InputList.Add(
'des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee');
InputList.Add('dw01 ieee dw01 dware gtech');
InputList.Add('dw02 ieee dw02 dware');
InputList.Add('dw03 std synopsys dware dw03 dw02 dw01 ieee gtech');
InputList.Add('dw04 dw04 ieee dw01 dware gtech');
InputList.Add('dw05 dw05 ieee dware');
InputList.Add('dw06 dw06 ieee dware');
InputList.Add('dw07 ieee dware');
InputList.Add('dware ieee dware');
InputList.Add('gtech ieee gtech');
InputList.Add('ramlib std ieee');
InputList.Add('std_cell_lib ieee std_cell_lib');
InputList.Add('synopsys');
TopSort := TTopologicalSort.Create;
OutputList := TStringList.Create;
try
TopSort.AddNodeDependencies(InputList);
TopSort.SortOrder(OutputList);
for Counter := 0 to OutputList.Count - 1 do
begin
writeln(OutputList[Counter]);
end;
except
on E: Exception do
begin
Writeln(stderr, 'Error: ', DateTimeToStr(Now),
': Error sorting. Technical details: ',
E.ClassName, '/', E.Message);
end;
end;
OutputList.Free;
TopSort.Free;
InputList.Free;
end.
| try:
from functools import reduce
except:
pass
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()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) ))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.