Task: Topological sort_Extracted top item




Go: package main

import (
    "fmt"
    "strings"
)

var data = `
FILE    FILE DEPENDENCIES
====    =================
top1    des1 ip1 ip2
top2    des1 ip2 ip3
ip1     extra1 ip1a ipcommon
ip2     ip2a ip2b ip2c ipcommon
des1    des1a des1b des1c
des1a   des1a1 des1a2
des1c   des1c1 extra1`

func main() {
    g, dep, err := parseLibDep(data)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    
    
    var tops []string
    for n := range g {
        if !dep[n] {
            tops = append(tops, n)
        }
    }
    fmt.Println("Top levels:", tops)
    
    showOrder(g, "top1")         
    showOrder(g, "top2")         
    showOrder(g, "top1", "top2") 

    fmt.Println("Cycle examples:")
    
    g, _, err = parseLibDep(data + `
des1a1  des1`)
    if err != nil {
        fmt.Println(err)
        return
    }
    showOrder(g, "top1")       
    showOrder(g, "ip1", "ip2") 
}

func showOrder(g graph, target ...string) {
    order, cyclic := g.orderFrom(target...)
    if cyclic == nil {
        reverse(order) 
        fmt.Println("Target", target, "order:", order)
    } else {
        fmt.Println("Target", target, "cyclic dependencies:", cyclic)
    }
}

func reverse(s []string) {
    last := len(s) - 1
    for i, e := range s[:len(s)/2] {
        s[i], s[last-i] = s[last-i], e
    }
}

type graph map[string][]string 
type depList map[string]bool



func parseLibDep(data string) (g graph, d depList, 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{}
    d = depList{}
    for _, line := range lines {
        libs := strings.Fields(line)
        if len(libs) == 0 {
            continue
        }
        lib := libs[0]
        var deps []string
        for _, dep := range libs[1:] {
            g[dep] = g[dep]
            if dep == lib {
                continue
            }
            for i := 0; ; i++ {
                if i == len(deps) {
                    deps = append(deps, dep)
                    d[dep] = true
                    break
                }
                if dep == deps[i] {
                    break
                }
            }
        }
        g[lib] = deps
    }
    return g, d, nil
}






func (g graph) orderFrom(start ...string) (order, cyclic []string) {
    L := make([]string, len(g))
    i := len(L)
    temp := map[string]bool{}
    perm := map[string]bool{}
    var cycleFound bool
    var cycleStart string
    var visit func(string)
    visit = func(n string) {
        switch {
        case temp[n]:
            cycleFound = true
            cycleStart = n
            return
        case perm[n]:
            return
        }
        temp[n] = true
        for _, m := range g[n] {
            visit(m)
            if cycleFound {
                if cycleStart > "" {
                    cyclic = append(cyclic, n)
                    if n == cycleStart {
                        cycleStart = ""
                    }
                }
                return
            }
        }
        delete(temp, n)
        perm[n] = true
        i--
        L[i] = n
    }
    for _, n := range start {
        if perm[n] {
            continue
        }
        visit(n)
        if cycleFound {
            return nil, cyclic
        }
    }
    return L[i:], nil
}


Java: import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;

public class TopologicalSort2 {

    public static void main(String[] args) {
        String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1,"
                + "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1";

        Graph g = new Graph(s, new int[][]{
            {0, 10}, {0, 2}, {0, 3},
            {1, 10}, {1, 3}, {1, 4},
            {2, 17}, {2, 5}, {2, 9},
            {3, 6}, {3, 7}, {3, 8}, {3, 9},
            {10, 11}, {10, 12}, {10, 13},
            {11, 14}, {11, 15},
            {13, 16}, {13, 17},});

        System.out.println("Top levels: " + g.toplevels());
        String[] files = {"top1", "top2", "ip1"};
        for (String f : files)
            System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f));
    }
}

class Graph {
    List<String> vertices;
    boolean[][] adjacency;
    int numVertices;

    public Graph(String s, int[][] edges) {
        vertices = asList(s.split(","));
        numVertices = vertices.size();
        adjacency = new boolean[numVertices][numVertices];

        for (int[] edge : edges)
            adjacency[edge[0]][edge[1]] = true;
    }

    List<String> toplevels() {
        List<String> result = new ArrayList<>();
        
        outer:
        for (int c = 0; c < numVertices; c++) {
            for (int r = 0; r < numVertices; r++) {
                if (adjacency[r][c])
                    continue outer;
            }
            result.add(vertices.get(c));
        }
        return result;
    }

    List<String> compileOrder(String item) {
        LinkedList<String> result = new LinkedList<>();
        LinkedList<Integer> queue = new LinkedList<>();

        queue.add(vertices.indexOf(item));

        while (!queue.isEmpty()) {
            int r = queue.poll();
            for (int c = 0; c < numVertices; c++) {
                if (adjacency[r][c] && !queue.contains(c)) {
                    queue.add(c);
                }
            }
            result.addFirst(vertices.get(r));
        }
        return result.stream().distinct().collect(toList());
    }
}