2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,26 +1,77 @@
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.*;
public class TopologicalSort {
public static void main(String[] args) throws Exception {
TreeMap<String, ArrayList<String>> mp = new TreeMap<String, ArrayList<String>>();
String[] data, input = new String[] {
"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:" };
for (String str : input)
mp.put((data = str.split(":"))[0], Utils.aList(//
data.length < 2 || data[1].trim().equals("")//
? null : data[1].trim().split("\\s+")));
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";
Utils.tSortFix(mp);
System.out.println(Utils.tSort(mp));
mp.put("dw01", Utils.aList("dw04"));
System.out.println(Utils.tSort(mp));
}
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}, {11, 10},
{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]);
// no need to worry about concurrent modification
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;
}
}