Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Can you help me rewrite this code in VB instead of Pascal, keeping it the same logically? | 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.
| 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
|
Change the programming language of this snippet from Pascal to Go without modifying what it does. | 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.
| 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 Perl implementation into C#, maintaining the same output and logic. | sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {
print "@afters\n";
delete @ba{@afters};
delete @{$_}{@afters} for values %ba;
}
print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n";
}
my %deps = (
des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee )],
dw01 => [qw( ieee dw01 dware gtech )],
dw02 => [qw( ieee dw02 dware )],
dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )],
dw04 => [qw( dw04 ieee dw01 dware gtech )],
dw05 => [qw( dw05 ieee dware )],
dw06 => [qw( dw06 ieee dware )],
dw07 => [qw( ieee dware )],
dware => [qw( ieee dware )],
gtech => [qw( ieee gtech )],
ramlib => [qw( std ieee )],
std_cell_lib => [qw( ieee std_cell_lib )],
synopsys => [qw( )],
);
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04';
print_topo_sort(%deps);
| 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...");
}
}
}
|
Please provide an equivalent version of this Perl code in C++. | sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {
print "@afters\n";
delete @ba{@afters};
delete @{$_}{@afters} for values %ba;
}
print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n";
}
my %deps = (
des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee )],
dw01 => [qw( ieee dw01 dware gtech )],
dw02 => [qw( ieee dw02 dware )],
dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )],
dw04 => [qw( dw04 ieee dw01 dware gtech )],
dw05 => [qw( dw05 ieee dware )],
dw06 => [qw( dw06 ieee dware )],
dw07 => [qw( ieee dware )],
dware => [qw( ieee dware )],
gtech => [qw( ieee gtech )],
ramlib => [qw( std ieee )],
std_cell_lib => [qw( ieee std_cell_lib )],
synopsys => [qw( )],
);
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04';
print_topo_sort(%deps);
| #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 Perl code snippet into Java without altering its behavior. | sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {
print "@afters\n";
delete @ba{@afters};
delete @{$_}{@afters} for values %ba;
}
print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n";
}
my %deps = (
des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee )],
dw01 => [qw( ieee dw01 dware gtech )],
dw02 => [qw( ieee dw02 dware )],
dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )],
dw04 => [qw( dw04 ieee dw01 dware gtech )],
dw05 => [qw( dw05 ieee dware )],
dw06 => [qw( dw06 ieee dware )],
dw07 => [qw( ieee dware )],
dware => [qw( ieee dware )],
gtech => [qw( ieee gtech )],
ramlib => [qw( std ieee )],
std_cell_lib => [qw( ieee std_cell_lib )],
synopsys => [qw( )],
);
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04';
print_topo_sort(%deps);
| 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 Perl code. | sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {
print "@afters\n";
delete @ba{@afters};
delete @{$_}{@afters} for values %ba;
}
print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n";
}
my %deps = (
des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee )],
dw01 => [qw( ieee dw01 dware gtech )],
dw02 => [qw( ieee dw02 dware )],
dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )],
dw04 => [qw( dw04 ieee dw01 dware gtech )],
dw05 => [qw( dw05 ieee dware )],
dw06 => [qw( dw06 ieee dware )],
dw07 => [qw( ieee dware )],
dware => [qw( ieee dware )],
gtech => [qw( ieee gtech )],
ramlib => [qw( std ieee )],
std_cell_lib => [qw( ieee std_cell_lib )],
synopsys => [qw( )],
);
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04';
print_topo_sort(%deps);
| 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) ))
|
Transform the following Perl implementation into VB, maintaining the same output and logic. | sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {
print "@afters\n";
delete @ba{@afters};
delete @{$_}{@afters} for values %ba;
}
print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n";
}
my %deps = (
des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee )],
dw01 => [qw( ieee dw01 dware gtech )],
dw02 => [qw( ieee dw02 dware )],
dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )],
dw04 => [qw( dw04 ieee dw01 dware gtech )],
dw05 => [qw( dw05 ieee dware )],
dw06 => [qw( dw06 ieee dware )],
dw07 => [qw( ieee dware )],
dware => [qw( ieee dware )],
gtech => [qw( ieee gtech )],
ramlib => [qw( std ieee )],
std_cell_lib => [qw( ieee std_cell_lib )],
synopsys => [qw( )],
);
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04';
print_topo_sort(%deps);
| 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 the same algorithm in Go as shown in this Perl implementation. | sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {
print "@afters\n";
delete @ba{@afters};
delete @{$_}{@afters} for values %ba;
}
print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n";
}
my %deps = (
des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee )],
dw01 => [qw( ieee dw01 dware gtech )],
dw02 => [qw( ieee dw02 dware )],
dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )],
dw04 => [qw( dw04 ieee dw01 dware gtech )],
dw05 => [qw( dw05 ieee dware )],
dw06 => [qw( dw06 ieee dware )],
dw07 => [qw( ieee dware )],
dware => [qw( ieee dware )],
gtech => [qw( ieee gtech )],
ramlib => [qw( std ieee )],
std_cell_lib => [qw( ieee std_cell_lib )],
synopsys => [qw( )],
);
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04';
print_topo_sort(%deps);
| 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. |
$a=@"
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
"@
$c = switch ( $a.split([char] 10) ) {
$_ {
$b=$_.split(' ')
New-Object PSObject -Property @{
Library = $b[0]
"Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
}
}
}
$c | ForEach-Object {
$_."Library Dependencies" | Where-Object {
$d=$_
$(:andl foreach($i in $c) {
if($d -match $i.Library) {
$false
break andl
}
}) -eq $null
} | ForEach-Object {
$c+=New-Object PSObject -Property @{
Library=$_
"Library Dependencies"=@()
}
}
}
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
Name="Dep Value"
Expression={
1
}
}
for( $i=0; $i -lt $d.count; $i++ ) {
$errmsg=""
foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
if( $k -match $d[$i].Library ) {
foreach( $n in $d[$i]."Library Dependencies" ) {
if( $n -match $d[$j].Library ) {
$errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
break
}
}
$true
break orl
}
} ) ) {
if( $j -lt $i ) {
foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
if( $m -match $d[$j].Library ) {
$true
break orl2
}
} ) ) {
$d[$l]."Dep Value"+=$d[$i]."Dep Value"
}
}
}
$d[$j]."Dep Value"+=$d[$i]."Dep Value"
}
if( $errmsg -ne "" ) {
$errmsg
$d=$null
break
}
}
}
if( $d ) {
$d | Sort "Dep Value",Library | ForEach-Object {
"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
} {
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
}
| #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;
}
|
Port the provided PowerShell code into C# while preserving the original functionality. |
$a=@"
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
"@
$c = switch ( $a.split([char] 10) ) {
$_ {
$b=$_.split(' ')
New-Object PSObject -Property @{
Library = $b[0]
"Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
}
}
}
$c | ForEach-Object {
$_."Library Dependencies" | Where-Object {
$d=$_
$(:andl foreach($i in $c) {
if($d -match $i.Library) {
$false
break andl
}
}) -eq $null
} | ForEach-Object {
$c+=New-Object PSObject -Property @{
Library=$_
"Library Dependencies"=@()
}
}
}
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
Name="Dep Value"
Expression={
1
}
}
for( $i=0; $i -lt $d.count; $i++ ) {
$errmsg=""
foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
if( $k -match $d[$i].Library ) {
foreach( $n in $d[$i]."Library Dependencies" ) {
if( $n -match $d[$j].Library ) {
$errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
break
}
}
$true
break orl
}
} ) ) {
if( $j -lt $i ) {
foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
if( $m -match $d[$j].Library ) {
$true
break orl2
}
} ) ) {
$d[$l]."Dep Value"+=$d[$i]."Dep Value"
}
}
}
$d[$j]."Dep Value"+=$d[$i]."Dep Value"
}
if( $errmsg -ne "" ) {
$errmsg
$d=$null
break
}
}
}
if( $d ) {
$d | Sort "Dep Value",Library | ForEach-Object {
"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
} {
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
}
| 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 PowerShell. |
$a=@"
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
"@
$c = switch ( $a.split([char] 10) ) {
$_ {
$b=$_.split(' ')
New-Object PSObject -Property @{
Library = $b[0]
"Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
}
}
}
$c | ForEach-Object {
$_."Library Dependencies" | Where-Object {
$d=$_
$(:andl foreach($i in $c) {
if($d -match $i.Library) {
$false
break andl
}
}) -eq $null
} | ForEach-Object {
$c+=New-Object PSObject -Property @{
Library=$_
"Library Dependencies"=@()
}
}
}
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
Name="Dep Value"
Expression={
1
}
}
for( $i=0; $i -lt $d.count; $i++ ) {
$errmsg=""
foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
if( $k -match $d[$i].Library ) {
foreach( $n in $d[$i]."Library Dependencies" ) {
if( $n -match $d[$j].Library ) {
$errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
break
}
}
$true
break orl
}
} ) ) {
if( $j -lt $i ) {
foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
if( $m -match $d[$j].Library ) {
$true
break orl2
}
} ) ) {
$d[$l]."Dep Value"+=$d[$i]."Dep Value"
}
}
}
$d[$j]."Dep Value"+=$d[$i]."Dep Value"
}
if( $errmsg -ne "" ) {
$errmsg
$d=$null
break
}
}
}
if( $d ) {
$d | Sort "Dep Value",Library | ForEach-Object {
"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
} {
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
}
| #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 PowerShell implementation into Java, maintaining the same output and logic. |
$a=@"
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
"@
$c = switch ( $a.split([char] 10) ) {
$_ {
$b=$_.split(' ')
New-Object PSObject -Property @{
Library = $b[0]
"Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
}
}
}
$c | ForEach-Object {
$_."Library Dependencies" | Where-Object {
$d=$_
$(:andl foreach($i in $c) {
if($d -match $i.Library) {
$false
break andl
}
}) -eq $null
} | ForEach-Object {
$c+=New-Object PSObject -Property @{
Library=$_
"Library Dependencies"=@()
}
}
}
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
Name="Dep Value"
Expression={
1
}
}
for( $i=0; $i -lt $d.count; $i++ ) {
$errmsg=""
foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
if( $k -match $d[$i].Library ) {
foreach( $n in $d[$i]."Library Dependencies" ) {
if( $n -match $d[$j].Library ) {
$errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
break
}
}
$true
break orl
}
} ) ) {
if( $j -lt $i ) {
foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
if( $m -match $d[$j].Library ) {
$true
break orl2
}
} ) ) {
$d[$l]."Dep Value"+=$d[$i]."Dep Value"
}
}
}
$d[$j]."Dep Value"+=$d[$i]."Dep Value"
}
if( $errmsg -ne "" ) {
$errmsg
$d=$null
break
}
}
}
if( $d ) {
$d | Sort "Dep Value",Library | ForEach-Object {
"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
} {
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
}
| 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;
}
}
|
Write a version of this PowerShell function in Python with identical behavior. |
$a=@"
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
"@
$c = switch ( $a.split([char] 10) ) {
$_ {
$b=$_.split(' ')
New-Object PSObject -Property @{
Library = $b[0]
"Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
}
}
}
$c | ForEach-Object {
$_."Library Dependencies" | Where-Object {
$d=$_
$(:andl foreach($i in $c) {
if($d -match $i.Library) {
$false
break andl
}
}) -eq $null
} | ForEach-Object {
$c+=New-Object PSObject -Property @{
Library=$_
"Library Dependencies"=@()
}
}
}
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
Name="Dep Value"
Expression={
1
}
}
for( $i=0; $i -lt $d.count; $i++ ) {
$errmsg=""
foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
if( $k -match $d[$i].Library ) {
foreach( $n in $d[$i]."Library Dependencies" ) {
if( $n -match $d[$j].Library ) {
$errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
break
}
}
$true
break orl
}
} ) ) {
if( $j -lt $i ) {
foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
if( $m -match $d[$j].Library ) {
$true
break orl2
}
} ) ) {
$d[$l]."Dep Value"+=$d[$i]."Dep Value"
}
}
}
$d[$j]."Dep Value"+=$d[$i]."Dep Value"
}
if( $errmsg -ne "" ) {
$errmsg
$d=$null
break
}
}
}
if( $d ) {
$d | Sort "Dep Value",Library | ForEach-Object {
"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
} {
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
}
| 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) ))
|
Transform the following PowerShell implementation into VB, maintaining the same output and logic. |
$a=@"
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
"@
$c = switch ( $a.split([char] 10) ) {
$_ {
$b=$_.split(' ')
New-Object PSObject -Property @{
Library = $b[0]
"Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
}
}
}
$c | ForEach-Object {
$_."Library Dependencies" | Where-Object {
$d=$_
$(:andl foreach($i in $c) {
if($d -match $i.Library) {
$false
break andl
}
}) -eq $null
} | ForEach-Object {
$c+=New-Object PSObject -Property @{
Library=$_
"Library Dependencies"=@()
}
}
}
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
Name="Dep Value"
Expression={
1
}
}
for( $i=0; $i -lt $d.count; $i++ ) {
$errmsg=""
foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
if( $k -match $d[$i].Library ) {
foreach( $n in $d[$i]."Library Dependencies" ) {
if( $n -match $d[$j].Library ) {
$errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
break
}
}
$true
break orl
}
} ) ) {
if( $j -lt $i ) {
foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
if( $m -match $d[$j].Library ) {
$true
break orl2
}
} ) ) {
$d[$l]."Dep Value"+=$d[$i]."Dep Value"
}
}
}
$d[$j]."Dep Value"+=$d[$i]."Dep Value"
}
if( $errmsg -ne "" ) {
$errmsg
$d=$null
break
}
}
}
if( $d ) {
$d | Sort "Dep Value",Library | ForEach-Object {
"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
} {
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
}
| 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 provided PowerShell code into Go while preserving the original functionality. |
$a=@"
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
"@
$c = switch ( $a.split([char] 10) ) {
$_ {
$b=$_.split(' ')
New-Object PSObject -Property @{
Library = $b[0]
"Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
}
}
}
$c | ForEach-Object {
$_."Library Dependencies" | Where-Object {
$d=$_
$(:andl foreach($i in $c) {
if($d -match $i.Library) {
$false
break andl
}
}) -eq $null
} | ForEach-Object {
$c+=New-Object PSObject -Property @{
Library=$_
"Library Dependencies"=@()
}
}
}
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
Name="Dep Value"
Expression={
1
}
}
for( $i=0; $i -lt $d.count; $i++ ) {
$errmsg=""
foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
if( $k -match $d[$i].Library ) {
foreach( $n in $d[$i]."Library Dependencies" ) {
if( $n -match $d[$j].Library ) {
$errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
break
}
}
$true
break orl
}
} ) ) {
if( $j -lt $i ) {
foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
if( $m -match $d[$j].Library ) {
$true
break orl2
}
} ) ) {
$d[$l]."Dep Value"+=$d[$i]."Dep Value"
}
}
}
$d[$j]."Dep Value"+=$d[$i]."Dep Value"
}
if( $errmsg -ne "" ) {
$errmsg
$d=$null
break
}
}
}
if( $d ) {
$d | Sort "Dep Value",Library | ForEach-Object {
"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
} {
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
}
| 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
}
|
Keep all operations the same but rewrite the snippet in C. | deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
| #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 R snippet to C# and keep its semantics consistent. | deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
| 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 R version. | deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
| #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()));
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
| 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 R snippet to Python and keep its semantics consistent. | deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
| 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 this program in VB while keeping its functionality equivalent to the R version. | deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
| 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 R snippet. | deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
| 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 Racket code in C. | #lang racket
(define G
(make-hash
'((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 (clean G)
(define G* (hash-copy G))
(for ([(from tos) G])
(hash-set! G* from (remove from tos))
(for ([to tos]) (hash-update! G* to (λ(_)_) '())))
G*)
(define (incoming G)
(define in (make-hash))
(for* ([(from tos) G] [to tos])
(hash-update! in to (λ(fs) (cons from fs)) '()))
in)
(define (nodes G) (hash-keys G))
(define (out G n) (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))
(define (topo-sort G)
(define n (length (nodes G)))
(define in (incoming G))
(define (no-incoming? n) (empty? (hash-ref in n '())))
(let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
(cond [(set-empty? S)
(if (= (length L) n)
L
(error 'topo-sort (~a "cycle detected" G)))]
[else
(define n (set-first S))
(define S\n (set-rest S))
(for ([m (out G n)])
(remove! G n m)
(remove! in m n)
(when (no-incoming? m)
(set! S\n (set-add S\n m))))
(loop (cons n L) S\n)])))
(topo-sort (clean G))
| #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 functionally identical C# code for the snippet given in Racket. | #lang racket
(define G
(make-hash
'((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 (clean G)
(define G* (hash-copy G))
(for ([(from tos) G])
(hash-set! G* from (remove from tos))
(for ([to tos]) (hash-update! G* to (λ(_)_) '())))
G*)
(define (incoming G)
(define in (make-hash))
(for* ([(from tos) G] [to tos])
(hash-update! in to (λ(fs) (cons from fs)) '()))
in)
(define (nodes G) (hash-keys G))
(define (out G n) (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))
(define (topo-sort G)
(define n (length (nodes G)))
(define in (incoming G))
(define (no-incoming? n) (empty? (hash-ref in n '())))
(let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
(cond [(set-empty? S)
(if (= (length L) n)
L
(error 'topo-sort (~a "cycle detected" G)))]
[else
(define n (set-first S))
(define S\n (set-rest S))
(for ([m (out G n)])
(remove! G n m)
(remove! in m n)
(when (no-incoming? m)
(set! S\n (set-add S\n m))))
(loop (cons n L) S\n)])))
(topo-sort (clean G))
| 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...");
}
}
}
|
Port the provided Racket code into C++ while preserving the original functionality. | #lang racket
(define G
(make-hash
'((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 (clean G)
(define G* (hash-copy G))
(for ([(from tos) G])
(hash-set! G* from (remove from tos))
(for ([to tos]) (hash-update! G* to (λ(_)_) '())))
G*)
(define (incoming G)
(define in (make-hash))
(for* ([(from tos) G] [to tos])
(hash-update! in to (λ(fs) (cons from fs)) '()))
in)
(define (nodes G) (hash-keys G))
(define (out G n) (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))
(define (topo-sort G)
(define n (length (nodes G)))
(define in (incoming G))
(define (no-incoming? n) (empty? (hash-ref in n '())))
(let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
(cond [(set-empty? S)
(if (= (length L) n)
L
(error 'topo-sort (~a "cycle detected" G)))]
[else
(define n (set-first S))
(define S\n (set-rest S))
(for ([m (out G n)])
(remove! G n m)
(remove! in m n)
(when (no-incoming? m)
(set! S\n (set-add S\n m))))
(loop (cons n L) S\n)])))
(topo-sort (clean G))
| #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 Racket code snippet into Java without altering its behavior. | #lang racket
(define G
(make-hash
'((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 (clean G)
(define G* (hash-copy G))
(for ([(from tos) G])
(hash-set! G* from (remove from tos))
(for ([to tos]) (hash-update! G* to (λ(_)_) '())))
G*)
(define (incoming G)
(define in (make-hash))
(for* ([(from tos) G] [to tos])
(hash-update! in to (λ(fs) (cons from fs)) '()))
in)
(define (nodes G) (hash-keys G))
(define (out G n) (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))
(define (topo-sort G)
(define n (length (nodes G)))
(define in (incoming G))
(define (no-incoming? n) (empty? (hash-ref in n '())))
(let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
(cond [(set-empty? S)
(if (= (length L) n)
L
(error 'topo-sort (~a "cycle detected" G)))]
[else
(define n (set-first S))
(define S\n (set-rest S))
(for ([m (out G n)])
(remove! G n m)
(remove! in m n)
(when (no-incoming? m)
(set! S\n (set-add S\n m))))
(loop (cons n L) S\n)])))
(topo-sort (clean G))
| 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;
}
}
|
Please provide an equivalent version of this Racket code in Python. | #lang racket
(define G
(make-hash
'((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 (clean G)
(define G* (hash-copy G))
(for ([(from tos) G])
(hash-set! G* from (remove from tos))
(for ([to tos]) (hash-update! G* to (λ(_)_) '())))
G*)
(define (incoming G)
(define in (make-hash))
(for* ([(from tos) G] [to tos])
(hash-update! in to (λ(fs) (cons from fs)) '()))
in)
(define (nodes G) (hash-keys G))
(define (out G n) (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))
(define (topo-sort G)
(define n (length (nodes G)))
(define in (incoming G))
(define (no-incoming? n) (empty? (hash-ref in n '())))
(let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
(cond [(set-empty? S)
(if (= (length L) n)
L
(error 'topo-sort (~a "cycle detected" G)))]
[else
(define n (set-first S))
(define S\n (set-rest S))
(for ([m (out G n)])
(remove! G n m)
(remove! in m n)
(when (no-incoming? m)
(set! S\n (set-add S\n m))))
(loop (cons n L) S\n)])))
(topo-sort (clean G))
| 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 Racket to VB. | #lang racket
(define G
(make-hash
'((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 (clean G)
(define G* (hash-copy G))
(for ([(from tos) G])
(hash-set! G* from (remove from tos))
(for ([to tos]) (hash-update! G* to (λ(_)_) '())))
G*)
(define (incoming G)
(define in (make-hash))
(for* ([(from tos) G] [to tos])
(hash-update! in to (λ(fs) (cons from fs)) '()))
in)
(define (nodes G) (hash-keys G))
(define (out G n) (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))
(define (topo-sort G)
(define n (length (nodes G)))
(define in (incoming G))
(define (no-incoming? n) (empty? (hash-ref in n '())))
(let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
(cond [(set-empty? S)
(if (= (length L) n)
L
(error 'topo-sort (~a "cycle detected" G)))]
[else
(define n (set-first S))
(define S\n (set-rest S))
(for ([m (out G n)])
(remove! G n m)
(remove! in m n)
(when (no-incoming? m)
(set! S\n (set-add S\n m))))
(loop (cons n L) S\n)])))
(topo-sort (clean G))
| 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 Racket, keeping it the same logically? | #lang racket
(define G
(make-hash
'((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 (clean G)
(define G* (hash-copy G))
(for ([(from tos) G])
(hash-set! G* from (remove from tos))
(for ([to tos]) (hash-update! G* to (λ(_)_) '())))
G*)
(define (incoming G)
(define in (make-hash))
(for* ([(from tos) G] [to tos])
(hash-update! in to (λ(fs) (cons from fs)) '()))
in)
(define (nodes G) (hash-keys G))
(define (out G n) (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))
(define (topo-sort G)
(define n (length (nodes G)))
(define in (incoming G))
(define (no-incoming? n) (empty? (hash-ref in n '())))
(let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
(cond [(set-empty? S)
(if (= (length L) n)
L
(error 'topo-sort (~a "cycle detected" G)))]
[else
(define n (set-first S))
(define S\n (set-rest S))
(for ([m (out G n)])
(remove! G n m)
(remove! in m n)
(when (no-incoming? m)
(set! S\n (set-add S\n m))))
(loop (cons n L) S\n)])))
(topo-sort (clean G))
| 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 REXX to C without modifying what it does. |
iDep.= 0; iPos.= 0; iOrd.= 0
nL= 15; nd= 44; nc= 69
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07' ,
'DWARE GTECH RAMLIB STD_CELL_LIB SYNOPSYS STD IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
do i=1
iL= word(iCode, i); if iL==0 then leave
do forever; i= i+1
iR= word(iCode, i); if iR==0 then leave
j= j+1; iDep.j.1= iL
iDep.j.2= iR
end
end
call tSort
say '═══compile order═══'
@= 'libraries found.)'
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
end
say ' ('# @; say
say '═══unordered libraries═══'
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
end
say ' ('# "unordered" @
exit
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
do i=1 for nL; iOrd.i= i; iPos.i= i
end
k= 1
do until k<=j; j = k; k= nL+1
do i=1 for nd; iL = iDep.i.1; iR= iPos.iL
ipL= iPos.iL; ipR= iPos.iR
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
k= k-1
_= iOrd.k; iPos._ = ipL
iPos.iL= k
iOrd.ipL= iOrd.k; iOrd.k = iL
end
end
nO= j-1; return
| #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 a version of this REXX function in C# with identical behavior. |
iDep.= 0; iPos.= 0; iOrd.= 0
nL= 15; nd= 44; nc= 69
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07' ,
'DWARE GTECH RAMLIB STD_CELL_LIB SYNOPSYS STD IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
do i=1
iL= word(iCode, i); if iL==0 then leave
do forever; i= i+1
iR= word(iCode, i); if iR==0 then leave
j= j+1; iDep.j.1= iL
iDep.j.2= iR
end
end
call tSort
say '═══compile order═══'
@= 'libraries found.)'
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
end
say ' ('# @; say
say '═══unordered libraries═══'
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
end
say ' ('# "unordered" @
exit
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
do i=1 for nL; iOrd.i= i; iPos.i= i
end
k= 1
do until k<=j; j = k; k= nL+1
do i=1 for nd; iL = iDep.i.1; iR= iPos.iL
ipL= iPos.iL; ipR= iPos.iR
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
k= k-1
_= iOrd.k; iPos._ = ipL
iPos.iL= k
iOrd.ipL= iOrd.k; iOrd.k = iL
end
end
nO= j-1; return
| 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 REXX snippet. |
iDep.= 0; iPos.= 0; iOrd.= 0
nL= 15; nd= 44; nc= 69
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07' ,
'DWARE GTECH RAMLIB STD_CELL_LIB SYNOPSYS STD IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
do i=1
iL= word(iCode, i); if iL==0 then leave
do forever; i= i+1
iR= word(iCode, i); if iR==0 then leave
j= j+1; iDep.j.1= iL
iDep.j.2= iR
end
end
call tSort
say '═══compile order═══'
@= 'libraries found.)'
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
end
say ' ('# @; say
say '═══unordered libraries═══'
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
end
say ' ('# "unordered" @
exit
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
do i=1 for nL; iOrd.i= i; iPos.i= i
end
k= 1
do until k<=j; j = k; k= nL+1
do i=1 for nd; iL = iDep.i.1; iR= iPos.iL
ipL= iPos.iL; ipR= iPos.iR
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
k= k-1
_= iOrd.k; iPos._ = ipL
iPos.iL= k
iOrd.ipL= iOrd.k; iOrd.k = iL
end
end
nO= j-1; return
| #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 REXX implementation. |
iDep.= 0; iPos.= 0; iOrd.= 0
nL= 15; nd= 44; nc= 69
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07' ,
'DWARE GTECH RAMLIB STD_CELL_LIB SYNOPSYS STD IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
do i=1
iL= word(iCode, i); if iL==0 then leave
do forever; i= i+1
iR= word(iCode, i); if iR==0 then leave
j= j+1; iDep.j.1= iL
iDep.j.2= iR
end
end
call tSort
say '═══compile order═══'
@= 'libraries found.)'
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
end
say ' ('# @; say
say '═══unordered libraries═══'
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
end
say ' ('# "unordered" @
exit
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
do i=1 for nL; iOrd.i= i; iPos.i= i
end
k= 1
do until k<=j; j = k; k= nL+1
do i=1 for nd; iL = iDep.i.1; iR= iPos.iL
ipL= iPos.iL; ipR= iPos.iR
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
k= k-1
_= iOrd.k; iPos._ = ipL
iPos.iL= k
iOrd.ipL= iOrd.k; iOrd.k = iL
end
end
nO= j-1; return
| 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 REXX to Python. |
iDep.= 0; iPos.= 0; iOrd.= 0
nL= 15; nd= 44; nc= 69
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07' ,
'DWARE GTECH RAMLIB STD_CELL_LIB SYNOPSYS STD IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
do i=1
iL= word(iCode, i); if iL==0 then leave
do forever; i= i+1
iR= word(iCode, i); if iR==0 then leave
j= j+1; iDep.j.1= iL
iDep.j.2= iR
end
end
call tSort
say '═══compile order═══'
@= 'libraries found.)'
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
end
say ' ('# @; say
say '═══unordered libraries═══'
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
end
say ' ('# "unordered" @
exit
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
do i=1 for nL; iOrd.i= i; iPos.i= i
end
k= 1
do until k<=j; j = k; k= nL+1
do i=1 for nd; iL = iDep.i.1; iR= iPos.iL
ipL= iPos.iL; ipR= iPos.iR
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
k= k-1
_= iOrd.k; iPos._ = ipL
iPos.iL= k
iOrd.ipL= iOrd.k; iOrd.k = iL
end
end
nO= j-1; return
| 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 the following code from REXX to VB, ensuring the logic remains intact. |
iDep.= 0; iPos.= 0; iOrd.= 0
nL= 15; nd= 44; nc= 69
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07' ,
'DWARE GTECH RAMLIB STD_CELL_LIB SYNOPSYS STD IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
do i=1
iL= word(iCode, i); if iL==0 then leave
do forever; i= i+1
iR= word(iCode, i); if iR==0 then leave
j= j+1; iDep.j.1= iL
iDep.j.2= iR
end
end
call tSort
say '═══compile order═══'
@= 'libraries found.)'
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
end
say ' ('# @; say
say '═══unordered libraries═══'
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
end
say ' ('# "unordered" @
exit
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
do i=1 for nL; iOrd.i= i; iPos.i= i
end
k= 1
do until k<=j; j = k; k= nL+1
do i=1 for nd; iL = iDep.i.1; iR= iPos.iL
ipL= iPos.iL; ipR= iPos.iR
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
k= k-1
_= iOrd.k; iPos._ = ipL
iPos.iL= k
iOrd.ipL= iOrd.k; iOrd.k = iL
end
end
nO= j-1; return
| 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 REXX function in Go with identical behavior. |
iDep.= 0; iPos.= 0; iOrd.= 0
nL= 15; nd= 44; nc= 69
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07' ,
'DWARE GTECH RAMLIB STD_CELL_LIB SYNOPSYS STD IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
do i=1
iL= word(iCode, i); if iL==0 then leave
do forever; i= i+1
iR= word(iCode, i); if iR==0 then leave
j= j+1; iDep.j.1= iL
iDep.j.2= iR
end
end
call tSort
say '═══compile order═══'
@= 'libraries found.)'
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
end
say ' ('# @; say
say '═══unordered libraries═══'
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
end
say ' ('# "unordered" @
exit
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
do i=1 for nL; iOrd.i= i; iPos.i= i
end
k= 1
do until k<=j; j = k; k= nL+1
do i=1 for nd; iL = iDep.i.1; iR= iPos.iL
ipL= iPos.iL; ipR= iPos.iR
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
k= k-1
_= iOrd.k; iPos._ = ipL
iPos.iL= k
iOrd.ipL= iOrd.k; iOrd.k = iL
end
end
nO= j-1; return
| 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 Ruby implementation into C, maintaining the same output and logic. | require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends["dw01"] << "dw04"
p depends.tsort
rescue TSort::Cyclic => e
puts "\ncycle detected:
end
__END__
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;
}
|
Change the programming language of this snippet from Ruby to C# without modifying what it does. | require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends["dw01"] << "dw04"
p depends.tsort
rescue TSort::Cyclic => e
puts "\ncycle detected:
end
__END__
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...");
}
}
}
|
Port the following code from Ruby to C++ with equivalent syntax and logic. | require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends["dw01"] << "dw04"
p depends.tsort
rescue TSort::Cyclic => e
puts "\ncycle detected:
end
__END__
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()));
}
}
|
Rewrite the snippet below in Java so it works the same as the original Ruby code. | require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends["dw01"] << "dw04"
p depends.tsort
rescue TSort::Cyclic => e
puts "\ncycle detected:
end
__END__
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;
}
}
|
Ensure the translated Python code behaves exactly like the original Ruby snippet. | require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends["dw01"] << "dw04"
p depends.tsort
rescue TSort::Cyclic => e
puts "\ncycle detected:
end
__END__
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) ))
|
Write the same code in VB as shown below in Ruby. | require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends["dw01"] << "dw04"
p depends.tsort
rescue TSort::Cyclic => e
puts "\ncycle detected:
end
__END__
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
|
Ensure the translated Go code behaves exactly like the original Ruby snippet. | require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends["dw01"] << "dw04"
p depends.tsort
rescue TSort::Cyclic => e
puts "\ncycle detected:
end
__END__
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
}
|
Produce a functionally identical C code for the snippet given in Scala. |
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
val deps = mutableListOf(
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
3 to 1, 3 to 10, 3 to 11,
4 to 1, 4 to 10,
5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
6 to 1, 6 to 3, 6 to 10, 6 to 11,
7 to 1, 7 to 10,
8 to 1, 8 to 10,
9 to 1, 9 to 10,
10 to 1,
11 to 1,
12 to 0, 12 to 1,
13 to 1
)
class Graph(s: String, edges: List<Pair<Int,Int>>) {
val vertices = s.split(", ")
val numVertices = vertices.size
val adjacency = List(numVertices) { BooleanArray(numVertices) }
init {
for (edge in edges) adjacency[edge.first][edge.second] = true
}
fun hasDependency(r: Int, todo: List<Int>): Boolean {
return todo.any { adjacency[r][it] }
}
fun topoSort(): List<String>? {
val result = mutableListOf<String>()
val todo = MutableList<Int>(numVertices) { it }
try {
outer@ while(!todo.isEmpty()) {
for ((i, r) in todo.withIndex()) {
if (!hasDependency(r, todo)) {
todo.removeAt(i)
result.add(vertices[r])
continue@outer
}
}
throw Exception("Graph has cycles")
}
}
catch (e: Exception) {
println(e)
return null
}
return result
}
}
fun main(args: Array<String>) {
val g = Graph(s, deps)
println("Topologically sorted order:")
println(g.topoSort())
println()
deps.add(10, 3 to 6)
val g2 = Graph(s, deps)
println("Following the addition of dw04 to the dependencies of dw01:")
println(g2.topoSort())
}
| #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 a version of this Scala function in C# with identical behavior. |
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
val deps = mutableListOf(
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
3 to 1, 3 to 10, 3 to 11,
4 to 1, 4 to 10,
5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
6 to 1, 6 to 3, 6 to 10, 6 to 11,
7 to 1, 7 to 10,
8 to 1, 8 to 10,
9 to 1, 9 to 10,
10 to 1,
11 to 1,
12 to 0, 12 to 1,
13 to 1
)
class Graph(s: String, edges: List<Pair<Int,Int>>) {
val vertices = s.split(", ")
val numVertices = vertices.size
val adjacency = List(numVertices) { BooleanArray(numVertices) }
init {
for (edge in edges) adjacency[edge.first][edge.second] = true
}
fun hasDependency(r: Int, todo: List<Int>): Boolean {
return todo.any { adjacency[r][it] }
}
fun topoSort(): List<String>? {
val result = mutableListOf<String>()
val todo = MutableList<Int>(numVertices) { it }
try {
outer@ while(!todo.isEmpty()) {
for ((i, r) in todo.withIndex()) {
if (!hasDependency(r, todo)) {
todo.removeAt(i)
result.add(vertices[r])
continue@outer
}
}
throw Exception("Graph has cycles")
}
}
catch (e: Exception) {
println(e)
return null
}
return result
}
}
fun main(args: Array<String>) {
val g = Graph(s, deps)
println("Topologically sorted order:")
println(g.topoSort())
println()
deps.add(10, 3 to 6)
val g2 = Graph(s, deps)
println("Following the addition of dw04 to the dependencies of dw01:")
println(g2.topoSort())
}
| 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 Scala snippet to C++ and keep its semantics consistent. |
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
val deps = mutableListOf(
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
3 to 1, 3 to 10, 3 to 11,
4 to 1, 4 to 10,
5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
6 to 1, 6 to 3, 6 to 10, 6 to 11,
7 to 1, 7 to 10,
8 to 1, 8 to 10,
9 to 1, 9 to 10,
10 to 1,
11 to 1,
12 to 0, 12 to 1,
13 to 1
)
class Graph(s: String, edges: List<Pair<Int,Int>>) {
val vertices = s.split(", ")
val numVertices = vertices.size
val adjacency = List(numVertices) { BooleanArray(numVertices) }
init {
for (edge in edges) adjacency[edge.first][edge.second] = true
}
fun hasDependency(r: Int, todo: List<Int>): Boolean {
return todo.any { adjacency[r][it] }
}
fun topoSort(): List<String>? {
val result = mutableListOf<String>()
val todo = MutableList<Int>(numVertices) { it }
try {
outer@ while(!todo.isEmpty()) {
for ((i, r) in todo.withIndex()) {
if (!hasDependency(r, todo)) {
todo.removeAt(i)
result.add(vertices[r])
continue@outer
}
}
throw Exception("Graph has cycles")
}
}
catch (e: Exception) {
println(e)
return null
}
return result
}
}
fun main(args: Array<String>) {
val g = Graph(s, deps)
println("Topologically sorted order:")
println(g.topoSort())
println()
deps.add(10, 3 to 6)
val g2 = Graph(s, deps)
println("Following the addition of dw04 to the dependencies of dw01:")
println(g2.topoSort())
}
| #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 Scala snippet. |
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
val deps = mutableListOf(
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
3 to 1, 3 to 10, 3 to 11,
4 to 1, 4 to 10,
5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
6 to 1, 6 to 3, 6 to 10, 6 to 11,
7 to 1, 7 to 10,
8 to 1, 8 to 10,
9 to 1, 9 to 10,
10 to 1,
11 to 1,
12 to 0, 12 to 1,
13 to 1
)
class Graph(s: String, edges: List<Pair<Int,Int>>) {
val vertices = s.split(", ")
val numVertices = vertices.size
val adjacency = List(numVertices) { BooleanArray(numVertices) }
init {
for (edge in edges) adjacency[edge.first][edge.second] = true
}
fun hasDependency(r: Int, todo: List<Int>): Boolean {
return todo.any { adjacency[r][it] }
}
fun topoSort(): List<String>? {
val result = mutableListOf<String>()
val todo = MutableList<Int>(numVertices) { it }
try {
outer@ while(!todo.isEmpty()) {
for ((i, r) in todo.withIndex()) {
if (!hasDependency(r, todo)) {
todo.removeAt(i)
result.add(vertices[r])
continue@outer
}
}
throw Exception("Graph has cycles")
}
}
catch (e: Exception) {
println(e)
return null
}
return result
}
}
fun main(args: Array<String>) {
val g = Graph(s, deps)
println("Topologically sorted order:")
println(g.topoSort())
println()
deps.add(10, 3 to 6)
val g2 = Graph(s, deps)
println("Following the addition of dw04 to the dependencies of dw01:")
println(g2.topoSort())
}
| 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. |
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
val deps = mutableListOf(
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
3 to 1, 3 to 10, 3 to 11,
4 to 1, 4 to 10,
5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
6 to 1, 6 to 3, 6 to 10, 6 to 11,
7 to 1, 7 to 10,
8 to 1, 8 to 10,
9 to 1, 9 to 10,
10 to 1,
11 to 1,
12 to 0, 12 to 1,
13 to 1
)
class Graph(s: String, edges: List<Pair<Int,Int>>) {
val vertices = s.split(", ")
val numVertices = vertices.size
val adjacency = List(numVertices) { BooleanArray(numVertices) }
init {
for (edge in edges) adjacency[edge.first][edge.second] = true
}
fun hasDependency(r: Int, todo: List<Int>): Boolean {
return todo.any { adjacency[r][it] }
}
fun topoSort(): List<String>? {
val result = mutableListOf<String>()
val todo = MutableList<Int>(numVertices) { it }
try {
outer@ while(!todo.isEmpty()) {
for ((i, r) in todo.withIndex()) {
if (!hasDependency(r, todo)) {
todo.removeAt(i)
result.add(vertices[r])
continue@outer
}
}
throw Exception("Graph has cycles")
}
}
catch (e: Exception) {
println(e)
return null
}
return result
}
}
fun main(args: Array<String>) {
val g = Graph(s, deps)
println("Topologically sorted order:")
println(g.topoSort())
println()
deps.add(10, 3 to 6)
val g2 = Graph(s, deps)
println("Following the addition of dw04 to the dependencies of dw01:")
println(g2.topoSort())
}
| 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 Scala to VB without modifying what it does. |
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
val deps = mutableListOf(
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
3 to 1, 3 to 10, 3 to 11,
4 to 1, 4 to 10,
5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
6 to 1, 6 to 3, 6 to 10, 6 to 11,
7 to 1, 7 to 10,
8 to 1, 8 to 10,
9 to 1, 9 to 10,
10 to 1,
11 to 1,
12 to 0, 12 to 1,
13 to 1
)
class Graph(s: String, edges: List<Pair<Int,Int>>) {
val vertices = s.split(", ")
val numVertices = vertices.size
val adjacency = List(numVertices) { BooleanArray(numVertices) }
init {
for (edge in edges) adjacency[edge.first][edge.second] = true
}
fun hasDependency(r: Int, todo: List<Int>): Boolean {
return todo.any { adjacency[r][it] }
}
fun topoSort(): List<String>? {
val result = mutableListOf<String>()
val todo = MutableList<Int>(numVertices) { it }
try {
outer@ while(!todo.isEmpty()) {
for ((i, r) in todo.withIndex()) {
if (!hasDependency(r, todo)) {
todo.removeAt(i)
result.add(vertices[r])
continue@outer
}
}
throw Exception("Graph has cycles")
}
}
catch (e: Exception) {
println(e)
return null
}
return result
}
}
fun main(args: Array<String>) {
val g = Graph(s, deps)
println("Topologically sorted order:")
println(g.topoSort())
println()
deps.add(10, 3 to 6)
val g2 = Graph(s, deps)
println("Following the addition of dw04 to the dependencies of dw01:")
println(g2.topoSort())
}
| 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
|
Preserve the algorithm and functionality while converting the code from Scala to Go. |
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
val deps = mutableListOf(
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
3 to 1, 3 to 10, 3 to 11,
4 to 1, 4 to 10,
5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
6 to 1, 6 to 3, 6 to 10, 6 to 11,
7 to 1, 7 to 10,
8 to 1, 8 to 10,
9 to 1, 9 to 10,
10 to 1,
11 to 1,
12 to 0, 12 to 1,
13 to 1
)
class Graph(s: String, edges: List<Pair<Int,Int>>) {
val vertices = s.split(", ")
val numVertices = vertices.size
val adjacency = List(numVertices) { BooleanArray(numVertices) }
init {
for (edge in edges) adjacency[edge.first][edge.second] = true
}
fun hasDependency(r: Int, todo: List<Int>): Boolean {
return todo.any { adjacency[r][it] }
}
fun topoSort(): List<String>? {
val result = mutableListOf<String>()
val todo = MutableList<Int>(numVertices) { it }
try {
outer@ while(!todo.isEmpty()) {
for ((i, r) in todo.withIndex()) {
if (!hasDependency(r, todo)) {
todo.removeAt(i)
result.add(vertices[r])
continue@outer
}
}
throw Exception("Graph has cycles")
}
}
catch (e: Exception) {
println(e)
return null
}
return result
}
}
fun main(args: Array<String>) {
val g = Graph(s, deps)
println("Topologically sorted order:")
println(g.topoSort())
println()
deps.add(10, 3 to 6)
val g2 = Graph(s, deps)
println("Following the addition of dw04 to the dependencies of dw01:")
println(g2.topoSort())
}
| 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 Swift snippet. | let 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", [])
]
struct Library {
var name: String
var children: [String]
var numParents: Int
}
func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
var libraries = [String: Library]()
for (name, parents) in input {
var numParents = 0
for parent in parents where parent != name {
numParents += 1
libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
}
libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
}
return libraries
}
func topologicalSort(libs: [String: Library]) -> [String]? {
var libs = libs
var needsProcessing = Set(libs.keys)
var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })
var sorted = [String]()
while let cur = options.popLast() {
for children in libs[cur]?.children ?? [] {
libs[children]?.numParents -= 1
if libs[children]?.numParents == 0 {
options.append(libs[children]!.name)
}
}
libs[cur]?.children.removeAll()
sorted.append(cur)
needsProcessing.remove(cur)
}
guard needsProcessing.isEmpty else {
return nil
}
return sorted
}
print(topologicalSort(libs: buildLibraries(libs))!)
| #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 functionally identical C# code for the snippet given in Swift. | let 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", [])
]
struct Library {
var name: String
var children: [String]
var numParents: Int
}
func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
var libraries = [String: Library]()
for (name, parents) in input {
var numParents = 0
for parent in parents where parent != name {
numParents += 1
libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
}
libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
}
return libraries
}
func topologicalSort(libs: [String: Library]) -> [String]? {
var libs = libs
var needsProcessing = Set(libs.keys)
var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })
var sorted = [String]()
while let cur = options.popLast() {
for children in libs[cur]?.children ?? [] {
libs[children]?.numParents -= 1
if libs[children]?.numParents == 0 {
options.append(libs[children]!.name)
}
}
libs[cur]?.children.removeAll()
sorted.append(cur)
needsProcessing.remove(cur)
}
guard needsProcessing.isEmpty else {
return nil
}
return sorted
}
print(topologicalSort(libs: buildLibraries(libs))!)
| 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 Swift. | let 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", [])
]
struct Library {
var name: String
var children: [String]
var numParents: Int
}
func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
var libraries = [String: Library]()
for (name, parents) in input {
var numParents = 0
for parent in parents where parent != name {
numParents += 1
libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
}
libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
}
return libraries
}
func topologicalSort(libs: [String: Library]) -> [String]? {
var libs = libs
var needsProcessing = Set(libs.keys)
var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })
var sorted = [String]()
while let cur = options.popLast() {
for children in libs[cur]?.children ?? [] {
libs[children]?.numParents -= 1
if libs[children]?.numParents == 0 {
options.append(libs[children]!.name)
}
}
libs[cur]?.children.removeAll()
sorted.append(cur)
needsProcessing.remove(cur)
}
guard needsProcessing.isEmpty else {
return nil
}
return sorted
}
print(topologicalSort(libs: buildLibraries(libs))!)
| #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 Swift implementation. | let 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", [])
]
struct Library {
var name: String
var children: [String]
var numParents: Int
}
func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
var libraries = [String: Library]()
for (name, parents) in input {
var numParents = 0
for parent in parents where parent != name {
numParents += 1
libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
}
libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
}
return libraries
}
func topologicalSort(libs: [String: Library]) -> [String]? {
var libs = libs
var needsProcessing = Set(libs.keys)
var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })
var sorted = [String]()
while let cur = options.popLast() {
for children in libs[cur]?.children ?? [] {
libs[children]?.numParents -= 1
if libs[children]?.numParents == 0 {
options.append(libs[children]!.name)
}
}
libs[cur]?.children.removeAll()
sorted.append(cur)
needsProcessing.remove(cur)
}
guard needsProcessing.isEmpty else {
return nil
}
return sorted
}
print(topologicalSort(libs: buildLibraries(libs))!)
| 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;
}
}
|
Ensure the translated Python code behaves exactly like the original Swift snippet. | let 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", [])
]
struct Library {
var name: String
var children: [String]
var numParents: Int
}
func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
var libraries = [String: Library]()
for (name, parents) in input {
var numParents = 0
for parent in parents where parent != name {
numParents += 1
libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
}
libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
}
return libraries
}
func topologicalSort(libs: [String: Library]) -> [String]? {
var libs = libs
var needsProcessing = Set(libs.keys)
var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })
var sorted = [String]()
while let cur = options.popLast() {
for children in libs[cur]?.children ?? [] {
libs[children]?.numParents -= 1
if libs[children]?.numParents == 0 {
options.append(libs[children]!.name)
}
}
libs[cur]?.children.removeAll()
sorted.append(cur)
needsProcessing.remove(cur)
}
guard needsProcessing.isEmpty else {
return nil
}
return sorted
}
print(topologicalSort(libs: buildLibraries(libs))!)
| 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 Swift snippet to VB and keep its semantics consistent. | let 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", [])
]
struct Library {
var name: String
var children: [String]
var numParents: Int
}
func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
var libraries = [String: Library]()
for (name, parents) in input {
var numParents = 0
for parent in parents where parent != name {
numParents += 1
libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
}
libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
}
return libraries
}
func topologicalSort(libs: [String: Library]) -> [String]? {
var libs = libs
var needsProcessing = Set(libs.keys)
var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })
var sorted = [String]()
while let cur = options.popLast() {
for children in libs[cur]?.children ?? [] {
libs[children]?.numParents -= 1
if libs[children]?.numParents == 0 {
options.append(libs[children]!.name)
}
}
libs[cur]?.children.removeAll()
sorted.append(cur)
needsProcessing.remove(cur)
}
guard needsProcessing.isEmpty else {
return nil
}
return sorted
}
print(topologicalSort(libs: buildLibraries(libs))!)
| 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 this program into Go but keep the logic exactly as in Swift. | let 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", [])
]
struct Library {
var name: String
var children: [String]
var numParents: Int
}
func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
var libraries = [String: Library]()
for (name, parents) in input {
var numParents = 0
for parent in parents where parent != name {
numParents += 1
libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
}
libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
}
return libraries
}
func topologicalSort(libs: [String: Library]) -> [String]? {
var libs = libs
var needsProcessing = Set(libs.keys)
var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })
var sorted = [String]()
while let cur = options.popLast() {
for children in libs[cur]?.children ?? [] {
libs[children]?.numParents -= 1
if libs[children]?.numParents == 0 {
options.append(libs[children]!.name)
}
}
libs[cur]?.children.removeAll()
sorted.append(cur)
needsProcessing.remove(cur)
}
guard needsProcessing.isEmpty else {
return nil
}
return sorted
}
print(topologicalSort(libs: buildLibraries(libs))!)
| 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 a version of this Tcl function in C with identical behavior. | package require Tcl 8.5
proc topsort {data} {
dict for {node depends} $data {
if {[set i [lsearch -exact $depends $node]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
foreach node $depends {dict lappend data $node}
}
set sorted {}
while 1 {
set avail [dict keys [dict filter $data value {}]]
if {![llength $avail]} {
if {[dict size $data]} {
error "graph is cyclic, possibly involving nodes \"[dict keys $data]\""
}
return $sorted
}
lappend sorted {*}[lsort $avail]
dict for {node depends} $data {
foreach n $avail {
if {[set i [lsearch -exact $depends $n]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
}
}
foreach node $avail {
dict unset data $node
}
}
}
| #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;
}
|
Preserve the algorithm and functionality while converting the code from Tcl to C#. | package require Tcl 8.5
proc topsort {data} {
dict for {node depends} $data {
if {[set i [lsearch -exact $depends $node]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
foreach node $depends {dict lappend data $node}
}
set sorted {}
while 1 {
set avail [dict keys [dict filter $data value {}]]
if {![llength $avail]} {
if {[dict size $data]} {
error "graph is cyclic, possibly involving nodes \"[dict keys $data]\""
}
return $sorted
}
lappend sorted {*}[lsort $avail]
dict for {node depends} $data {
foreach n $avail {
if {[set i [lsearch -exact $depends $n]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
}
}
foreach node $avail {
dict unset data $node
}
}
}
| 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 a version of this Tcl function in C++ with identical behavior. | package require Tcl 8.5
proc topsort {data} {
dict for {node depends} $data {
if {[set i [lsearch -exact $depends $node]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
foreach node $depends {dict lappend data $node}
}
set sorted {}
while 1 {
set avail [dict keys [dict filter $data value {}]]
if {![llength $avail]} {
if {[dict size $data]} {
error "graph is cyclic, possibly involving nodes \"[dict keys $data]\""
}
return $sorted
}
lappend sorted {*}[lsort $avail]
dict for {node depends} $data {
foreach n $avail {
if {[set i [lsearch -exact $depends $n]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
}
}
foreach node $avail {
dict unset data $node
}
}
}
| #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()));
}
}
|
Rewrite the snippet below in Java so it works the same as the original Tcl code. | package require Tcl 8.5
proc topsort {data} {
dict for {node depends} $data {
if {[set i [lsearch -exact $depends $node]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
foreach node $depends {dict lappend data $node}
}
set sorted {}
while 1 {
set avail [dict keys [dict filter $data value {}]]
if {![llength $avail]} {
if {[dict size $data]} {
error "graph is cyclic, possibly involving nodes \"[dict keys $data]\""
}
return $sorted
}
lappend sorted {*}[lsort $avail]
dict for {node depends} $data {
foreach n $avail {
if {[set i [lsearch -exact $depends $n]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
}
}
foreach node $avail {
dict unset data $node
}
}
}
| 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;
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Tcl version. | package require Tcl 8.5
proc topsort {data} {
dict for {node depends} $data {
if {[set i [lsearch -exact $depends $node]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
foreach node $depends {dict lappend data $node}
}
set sorted {}
while 1 {
set avail [dict keys [dict filter $data value {}]]
if {![llength $avail]} {
if {[dict size $data]} {
error "graph is cyclic, possibly involving nodes \"[dict keys $data]\""
}
return $sorted
}
lappend sorted {*}[lsort $avail]
dict for {node depends} $data {
foreach n $avail {
if {[set i [lsearch -exact $depends $n]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
}
}
foreach node $avail {
dict unset data $node
}
}
}
| 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 this program into VB but keep the logic exactly as in Tcl. | package require Tcl 8.5
proc topsort {data} {
dict for {node depends} $data {
if {[set i [lsearch -exact $depends $node]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
foreach node $depends {dict lappend data $node}
}
set sorted {}
while 1 {
set avail [dict keys [dict filter $data value {}]]
if {![llength $avail]} {
if {[dict size $data]} {
error "graph is cyclic, possibly involving nodes \"[dict keys $data]\""
}
return $sorted
}
lappend sorted {*}[lsort $avail]
dict for {node depends} $data {
foreach n $avail {
if {[set i [lsearch -exact $depends $n]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
}
}
foreach node $avail {
dict unset data $node
}
}
}
| 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 Tcl, keeping it the same logically? | package require Tcl 8.5
proc topsort {data} {
dict for {node depends} $data {
if {[set i [lsearch -exact $depends $node]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
foreach node $depends {dict lappend data $node}
}
set sorted {}
while 1 {
set avail [dict keys [dict filter $data value {}]]
if {![llength $avail]} {
if {[dict size $data]} {
error "graph is cyclic, possibly involving nodes \"[dict keys $data]\""
}
return $sorted
}
lappend sorted {*}[lsort $avail]
dict for {node depends} $data {
foreach n $avail {
if {[set i [lsearch -exact $depends $n]] >= 0} {
set depends [lreplace $depends $i $i]
dict set data $node $depends
}
}
}
foreach node $avail {
dict unset data $node
}
}
}
| 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 C to Rust, ensuring the logic remains intact. | #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;
}
| use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\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",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
|
Produce a functionally identical Rust code for the snippet given in C++. | #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()));
}
}
| use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\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",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
|
Rewrite the snippet below in Rust so it works the same as the original C# code. | 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...");
}
}
}
| use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\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",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
|
Can you help me rewrite this code in Rust instead of Java, keeping it the same logically? | 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;
}
}
| use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\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",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
|
Rewrite the snippet below in Rust so it works the same as the original Go code. | 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
}
| use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\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",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
|
Change the following Rust code into VB without altering its purpose. | use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\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",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
| 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 the same code in Python as shown below in Rust. | use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\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",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
| 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 a version of this Ada function in C# with identical behavior. | with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;
| class Program
{
static void Main(string[] args)
{
float myNumbers = 7.125F;
string strnumber = Convert.ToString(myNumbers);
Console.WriteLine(strnumber.PadLeft(9, '0'));
Console.ReadLine();
}
}
|
Write a version of this Ada function in C with identical behavior. | with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;
| #include <stdio.h>
main(){
float r=7.125;
printf(" %9.3f\n",-r);
printf(" %9.3f\n",r);
printf(" %-9.3f\n",r);
printf(" %09.3f\n",-r);
printf(" %09.3f\n",r);
printf(" %-09.3f\n",r);
return 0;
}
|
Please provide an equivalent version of this Ada code in C++. | with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;
| #include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setfill('0') << std::setw(9) << std::fixed << std::setprecision(3) << 7.125 << std::endl;
return 0;
}
|
Produce a functionally identical Go code for the snippet given in Ada. | with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;
| fmt.Printf("%09.3f", 7.125)
|
Port the following code from Ada to Java with equivalent syntax and logic. | with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;
| public class Printing{
public static void main(String[] args){
double value = 7.125;
System.out.printf("%09.3f",value);
System.out.println(String.format("%09.3f",value));
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Ada version. | with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;
| from math import pi, exp
r = exp(pi)-pi
print r
print "e=%e f=%f g=%g G=%G s=%s r=%r!"%(r,r,r,r,r,r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(-r,-r,-r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(r,r,r)
print "e=%-9.4e f=%-9.4f g=%-9.4g!"%(r,r,r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(-r,-r,-r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(r,r,r)
print "e=%-09.4e f=%-09.4f g=%-09.4g!"%(r,r,r)
|
Port the following code from Ada to VB with equivalent syntax and logic. | with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;
| Option Explicit
Sub Main()
Debug.Print fFormat(13, 2, 1230.3333)
Debug.Print fFormat(2, 13, 1230.3333)
Debug.Print fFormat(10, 5, 0.3333)
Debug.Print fFormat(13, 2, 1230)
End Sub
Private Function fFormat(NbInt As Integer, NbDec As Integer, Nb As Double) As String
Dim u As String, v As String, i As Integer
u = CStr(Nb)
i = InStr(u, Application.DecimalSeparator)
If i > 0 Then
v = Mid(u, i + 1)
u = Left(u, i - 1)
fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & Left(v & String(NbDec, "0"), NbDec)
Else
fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & String(NbDec, "0")
End If
End Function
|
Write a version of this Arturo function in C with identical behavior. | r: 7.125
print r
print to :string .format: "09.3f" r
| #include <stdio.h>
main(){
float r=7.125;
printf(" %9.3f\n",-r);
printf(" %9.3f\n",r);
printf(" %-9.3f\n",r);
printf(" %09.3f\n",-r);
printf(" %09.3f\n",r);
printf(" %-09.3f\n",r);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Arturo snippet. | r: 7.125
print r
print to :string .format: "09.3f" r
| class Program
{
static void Main(string[] args)
{
float myNumbers = 7.125F;
string strnumber = Convert.ToString(myNumbers);
Console.WriteLine(strnumber.PadLeft(9, '0'));
Console.ReadLine();
}
}
|
Generate a C++ translation of this Arturo snippet without changing its computational steps. | r: 7.125
print r
print to :string .format: "09.3f" r
| #include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setfill('0') << std::setw(9) << std::fixed << std::setprecision(3) << 7.125 << std::endl;
return 0;
}
|
Produce a language-to-language conversion: from Arturo to Java, same semantics. | r: 7.125
print r
print to :string .format: "09.3f" r
| public class Printing{
public static void main(String[] args){
double value = 7.125;
System.out.printf("%09.3f",value);
System.out.println(String.format("%09.3f",value));
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Arturo version. | r: 7.125
print r
print to :string .format: "09.3f" r
| from math import pi, exp
r = exp(pi)-pi
print r
print "e=%e f=%f g=%g G=%G s=%s r=%r!"%(r,r,r,r,r,r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(-r,-r,-r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(r,r,r)
print "e=%-9.4e f=%-9.4f g=%-9.4g!"%(r,r,r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(-r,-r,-r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(r,r,r)
print "e=%-09.4e f=%-09.4f g=%-09.4g!"%(r,r,r)
|
Ensure the translated VB code behaves exactly like the original Arturo snippet. | r: 7.125
print r
print to :string .format: "09.3f" r
| Option Explicit
Sub Main()
Debug.Print fFormat(13, 2, 1230.3333)
Debug.Print fFormat(2, 13, 1230.3333)
Debug.Print fFormat(10, 5, 0.3333)
Debug.Print fFormat(13, 2, 1230)
End Sub
Private Function fFormat(NbInt As Integer, NbDec As Integer, Nb As Double) As String
Dim u As String, v As String, i As Integer
u = CStr(Nb)
i = InStr(u, Application.DecimalSeparator)
If i > 0 Then
v = Mid(u, i + 1)
u = Left(u, i - 1)
fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & Left(v & String(NbDec, "0"), NbDec)
Else
fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & String(NbDec, "0")
End If
End Function
|
Preserve the algorithm and functionality while converting the code from Arturo to Go. | r: 7.125
print r
print to :string .format: "09.3f" r
| fmt.Printf("%09.3f", 7.125)
|
Rewrite this program in C while keeping its functionality equivalent to the AutoHotKey version. | MsgBox % pad(7.25,7)
MsgBox % pad(-7.25,7)
pad(x,len) {
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}
| #include <stdio.h>
main(){
float r=7.125;
printf(" %9.3f\n",-r);
printf(" %9.3f\n",r);
printf(" %-9.3f\n",r);
printf(" %09.3f\n",-r);
printf(" %09.3f\n",r);
printf(" %-09.3f\n",r);
return 0;
}
|
Generate a C# translation of this AutoHotKey snippet without changing its computational steps. | MsgBox % pad(7.25,7)
MsgBox % pad(-7.25,7)
pad(x,len) {
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}
| class Program
{
static void Main(string[] args)
{
float myNumbers = 7.125F;
string strnumber = Convert.ToString(myNumbers);
Console.WriteLine(strnumber.PadLeft(9, '0'));
Console.ReadLine();
}
}
|
Produce a functionally identical C++ code for the snippet given in AutoHotKey. | MsgBox % pad(7.25,7)
MsgBox % pad(-7.25,7)
pad(x,len) {
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}
| #include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setfill('0') << std::setw(9) << std::fixed << std::setprecision(3) << 7.125 << std::endl;
return 0;
}
|
Can you help me rewrite this code in Java instead of AutoHotKey, keeping it the same logically? | MsgBox % pad(7.25,7)
MsgBox % pad(-7.25,7)
pad(x,len) {
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}
| public class Printing{
public static void main(String[] args){
double value = 7.125;
System.out.printf("%09.3f",value);
System.out.println(String.format("%09.3f",value));
}
}
|
Translate this program into Python but keep the logic exactly as in AutoHotKey. | MsgBox % pad(7.25,7)
MsgBox % pad(-7.25,7)
pad(x,len) {
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}
| from math import pi, exp
r = exp(pi)-pi
print r
print "e=%e f=%f g=%g G=%G s=%s r=%r!"%(r,r,r,r,r,r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(-r,-r,-r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(r,r,r)
print "e=%-9.4e f=%-9.4f g=%-9.4g!"%(r,r,r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(-r,-r,-r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(r,r,r)
print "e=%-09.4e f=%-09.4f g=%-09.4g!"%(r,r,r)
|
Preserve the algorithm and functionality while converting the code from AutoHotKey to VB. | MsgBox % pad(7.25,7)
MsgBox % pad(-7.25,7)
pad(x,len) {
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}
| Option Explicit
Sub Main()
Debug.Print fFormat(13, 2, 1230.3333)
Debug.Print fFormat(2, 13, 1230.3333)
Debug.Print fFormat(10, 5, 0.3333)
Debug.Print fFormat(13, 2, 1230)
End Sub
Private Function fFormat(NbInt As Integer, NbDec As Integer, Nb As Double) As String
Dim u As String, v As String, i As Integer
u = CStr(Nb)
i = InStr(u, Application.DecimalSeparator)
If i > 0 Then
v = Mid(u, i + 1)
u = Left(u, i - 1)
fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & Left(v & String(NbDec, "0"), NbDec)
Else
fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & String(NbDec, "0")
End If
End Function
|
Change the following AutoHotKey code into Go without altering its purpose. | MsgBox % pad(7.25,7)
MsgBox % pad(-7.25,7)
pad(x,len) {
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}
| fmt.Printf("%09.3f", 7.125)
|
Preserve the algorithm and functionality while converting the code from AWK to C. | BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-09.3f\n",r
}
| #include <stdio.h>
main(){
float r=7.125;
printf(" %9.3f\n",-r);
printf(" %9.3f\n",r);
printf(" %-9.3f\n",r);
printf(" %09.3f\n",-r);
printf(" %09.3f\n",r);
printf(" %-09.3f\n",r);
return 0;
}
|
Transform the following AWK implementation into C#, maintaining the same output and logic. | BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-09.3f\n",r
}
| class Program
{
static void Main(string[] args)
{
float myNumbers = 7.125F;
string strnumber = Convert.ToString(myNumbers);
Console.WriteLine(strnumber.PadLeft(9, '0'));
Console.ReadLine();
}
}
|
Generate an equivalent C++ version of this AWK code. | BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-09.3f\n",r
}
| #include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setfill('0') << std::setw(9) << std::fixed << std::setprecision(3) << 7.125 << std::endl;
return 0;
}
|
Can you help me rewrite this code in Java instead of AWK, keeping it the same logically? | BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-09.3f\n",r
}
| public class Printing{
public static void main(String[] args){
double value = 7.125;
System.out.printf("%09.3f",value);
System.out.println(String.format("%09.3f",value));
}
}
|
Write the same code in Python as shown below in AWK. | BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-09.3f\n",r
}
| from math import pi, exp
r = exp(pi)-pi
print r
print "e=%e f=%f g=%g G=%G s=%s r=%r!"%(r,r,r,r,r,r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(-r,-r,-r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(r,r,r)
print "e=%-9.4e f=%-9.4f g=%-9.4g!"%(r,r,r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(-r,-r,-r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(r,r,r)
print "e=%-09.4e f=%-09.4f g=%-09.4g!"%(r,r,r)
|
Convert this AWK snippet to VB and keep its semantics consistent. | BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-09.3f\n",r
}
| Option Explicit
Sub Main()
Debug.Print fFormat(13, 2, 1230.3333)
Debug.Print fFormat(2, 13, 1230.3333)
Debug.Print fFormat(10, 5, 0.3333)
Debug.Print fFormat(13, 2, 1230)
End Sub
Private Function fFormat(NbInt As Integer, NbDec As Integer, Nb As Double) As String
Dim u As String, v As String, i As Integer
u = CStr(Nb)
i = InStr(u, Application.DecimalSeparator)
If i > 0 Then
v = Mid(u, i + 1)
u = Left(u, i - 1)
fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & Left(v & String(NbDec, "0"), NbDec)
Else
fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & String(NbDec, "0")
End If
End Function
|
Keep all operations the same but rewrite the snippet in Go. | BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-09.3f\n",r
}
| fmt.Printf("%09.3f", 7.125)
|
Write the same code in C as shown below in BBC_Basic. | PRINT FNformat(PI, 9, 3)
PRINT FNformat(-PI, 9, 3)
END
DEF FNformat(n, sl%, dp%)
LOCAL @%
@% = &1020000 OR dp% << 8
IF n >= 0 THEN
= RIGHT$(STRING$(sl%,"0") + STR$(n), sl%)
ENDIF
= "-" + RIGHT$(STRING$(sl%,"0") + STR$(-n), sl%-1)
| #include <stdio.h>
main(){
float r=7.125;
printf(" %9.3f\n",-r);
printf(" %9.3f\n",r);
printf(" %-9.3f\n",r);
printf(" %09.3f\n",-r);
printf(" %09.3f\n",r);
printf(" %-09.3f\n",r);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.