Search in sources :

Example 1 with Queue

use of chapter1.section3.Queue in project algorithms-sedgewick-wayne by reneargento.

the class Exercise41_CopyQueue method main.

public static void main(String[] args) {
    Queue<Integer> originalQueue = new Queue<>();
    originalQueue.enqueue(1);
    originalQueue.enqueue(2);
    originalQueue.enqueue(3);
    originalQueue.enqueue(4);
    Exercise41_CopyQueue<Integer> queueCopy = new Exercise41_CopyQueue<>(originalQueue);
    queueCopy.enqueue(5);
    queueCopy.enqueue(99);
    originalQueue.dequeue();
    queueCopy.dequeue();
    queueCopy.dequeue();
    StringJoiner originalQueueItems = new StringJoiner(" ");
    for (int item : originalQueue) {
        originalQueueItems.add(String.valueOf(item));
    }
    StdOut.println("Original Queue: " + originalQueueItems.toString());
    StdOut.println("Expected: 2 3 4");
    StdOut.println();
    StringJoiner copyQueueItems = new StringJoiner(" ");
    for (int item : queueCopy) {
        copyQueueItems.add(String.valueOf(item));
    }
    StdOut.println("Queue Copy: " + copyQueueItems.toString());
    StdOut.println("Expected: 3 4 5 99");
}
Also used : Queue(edu.princeton.cs.algs4.Queue) StringJoiner(java.util.StringJoiner)

Example 2 with Queue

use of chapter1.section3.Queue in project algorithms-sedgewick-wayne by reneargento.

the class Exercise7 method keyIndexedCountWithQueue.

public void keyIndexedCountWithQueue(String[] array, int stringsLength) {
    // Extended ASCII characters
    int alphabetSize = 256;
    Queue<String> auxQueue = new Queue<>();
    Queue<String>[] count = new Queue[alphabetSize + 1];
    for (int r = 0; r < count.length; r++) {
        count[r] = new Queue();
    }
    for (int digit = stringsLength - 1; digit >= 0; digit--) {
        // Compute frequency counts
        for (int i = 0; i < array.length; i++) {
            int digitIndex = array[i].charAt(digit);
            count[digitIndex].enqueue(array[i]);
        }
        // Distribute
        for (int r = 0; r < count.length; r++) {
            while (!count[r].isEmpty()) {
                String string = count[r].dequeue();
                auxQueue.enqueue(string);
            }
        }
        // Copy back
        int indexArray = 0;
        while (!auxQueue.isEmpty()) {
            array[indexArray++] = auxQueue.dequeue();
        }
    }
}
Also used : Queue(chapter1.section3.Queue)

Example 3 with Queue

use of chapter1.section3.Queue in project AlgorithmsSolutions by Allenskoo856.

the class LookupIndex method main.

public static void main(String[] args) {
    In in = new In(args[0]);
    String sp = args[1];
    ST<String, Queue<String>> st = new ST<String, Queue<String>>();
    ST<String, Queue<String>> ts = new ST<String, Queue<String>>();
    while (in.hasNextLine()) {
        String[] a = in.readLine().split(sp);
        String key = a[0];
        for (int i = 1; i < a.length; i++) {
            String val = a[i];
            if (!st.contains(key)) {
                st.put(key, new Queue<String>());
            }
            if (!ts.contains(val)) {
                ts.put(val, new Queue<String>());
            }
            st.get(key).enqueue(val);
            ts.get(val).enqueue(key);
        }
    }
    while (!StdIn.isEmpty()) {
        String query = StdIn.readLine();
        if (st.contains(query)) {
            for (String s : st.get(query)) {
                StdOut.println(" " + s);
            }
        }
        if (ts.contains(query)) {
            for (String s : ts.get(query)) {
                StdOut.println(" " + s);
            }
        }
    }
}
Also used : ST(edu.princeton.cs.algs4.ST) StdIn(edu.princeton.cs.algs4.StdIn) In(edu.princeton.cs.algs4.In) Queue(com.jimmysun.algorithms.chapter1_3.Queue)

Example 4 with Queue

use of chapter1.section3.Queue in project algorithms-sedgewick-wayne by reneargento.

the class Exercise26_CriticalEdges method findCriticalEdges.

/**
 * An edge e is critical if and only if it is a bridge in the subgraph containing all edges with weights
 * less than or equal to the weight of edge e.
 *
 * Proof:
 * 1st part: If an edge e is critical then it is a bridge in the subgraph containing all edges with weights
 * less than or equal to the weight of edge e.
 * Consider by contradiction that edge e is not a bridge in such subgraph. If it is not a bridge, then there is another
 * edge f that connects the same components as e in the subgraph and it has weight less than or equal to e.
 * In this case, edge e could be replaced by edge f in an MST and the MST weight would not increase.
 * However, since e is critical and cannot be replaced by an edge with weight less than or equal to it,
 * it must be a bridge in the subgraph.
 *
 * 2nd part: If an edge e is a bridge in the subgraph containing all edges with weights less than or equal to its
 * weight then e is critical.
 * Consider by contradiction that e is not critical. If e is not critical, then there must be another edge that
 * could replace it in an MST and would not cause the MST weight to increase.
 * However, if this edge existed, it would be part of the subgraph containing all edges with weights
 * less than or equal to the weight of edge e. It would also connect both components C1 and C2 that are connected
 * by edge e. However, e is a bridge and its removal would split components C1 and C2. So no such edge exists.
 * Therefore, edge e is critical.
 */
// O(E lg E)
public Queue<Edge> findCriticalEdges(EdgeWeightedGraph edgeWeightedGraph) {
    Queue<Edge> criticalEdges = new Queue<>();
    // Modified Kruskal's algorithm
    Queue<Edge> minimumSpanningTree = new Queue<>();
    PriorityQueueResize<Edge> priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);
    for (Edge edge : edgeWeightedGraph.edges()) {
        priorityQueue.insert(edge);
    }
    UnionFind unionFind = new UnionFind(edgeWeightedGraph.vertices());
    // Subgraph with components
    EdgeWeightedGraphWithDelete componentsSubGraph = new EdgeWeightedGraphWithDelete(unionFind.count());
    while (!priorityQueue.isEmpty() && minimumSpanningTree.size() < edgeWeightedGraph.vertices() - 1) {
        Edge edge = priorityQueue.deleteTop();
        int vertex1 = edge.either();
        int vertex2 = edge.other(vertex1);
        // Ineligible edges are never critical edges
        if (unionFind.connected(vertex1, vertex2)) {
            continue;
        }
        // Get next equal-weight edge block
        double currentWeight = edge.weight();
        HashSet<Edge> equalWeightEdges = new HashSet<>();
        equalWeightEdges.add(edge);
        while (!priorityQueue.isEmpty() && priorityQueue.peek().weight() == currentWeight) {
            equalWeightEdges.add(priorityQueue.deleteTop());
        }
        if (equalWeightEdges.size() == 1) {
            // There is no cycle, so this is a critical edge
            criticalEdges.enqueue(edge);
            unionFind.union(vertex1, vertex2);
            minimumSpanningTree.enqueue(edge);
            continue;
        }
        List<Edge> edgesToAddToComponentsSubGraph = new ArrayList<>();
        // Map to make the mapping between edges in the components subgraph and the original graph
        int averageMapListSize = Math.max(2, equalWeightEdges.size() / 20);
        SeparateChainingHashTable<Edge, Edge> subGraphToGraphEdgeMap = new SeparateChainingHashTable<>(equalWeightEdges.size(), averageMapListSize);
        HashSet<Integer> verticesInSubGraph = new HashSet<>();
        // Generate subgraph with the current components
        for (Edge edgeInCurrentBlock : equalWeightEdges.keys()) {
            vertex1 = edgeInCurrentBlock.either();
            vertex2 = edgeInCurrentBlock.other(vertex1);
            int component1 = unionFind.find(vertex1);
            int component2 = unionFind.find(vertex2);
            Edge subGraphEdge = new Edge(component1, component2, currentWeight);
            edgesToAddToComponentsSubGraph.add(subGraphEdge);
            subGraphToGraphEdgeMap.put(subGraphEdge, edgeInCurrentBlock);
            verticesInSubGraph.add(component1);
            verticesInSubGraph.add(component2);
        }
        for (Edge edgeToAddToComponentSubGraph : edgesToAddToComponentsSubGraph) {
            componentsSubGraph.addEdge(edgeToAddToComponentSubGraph);
        }
        // Run DFS to check if there is a cycle. Any edges in the cycle are non-critical.
        // Every edge in the original graph will be visited by a DFS at most once.
        HashSet<Edge> nonCriticalEdges = new HashSet<>();
        // Use a different constructor for EdgeWeightedCycle to avoid O(E * V) runtime
        EdgeWeightedCycle edgeWeightedCycle = new EdgeWeightedCycle(componentsSubGraph, verticesInSubGraph);
        if (edgeWeightedCycle.hasCycle()) {
            for (Edge edgeInCycle : edgeWeightedCycle.cycle()) {
                Edge edgeInGraph = subGraphToGraphEdgeMap.get(edgeInCycle);
                nonCriticalEdges.add(edgeInGraph);
            }
        }
        // Clear components subgraph edges
        for (Edge edgeToAddToComponentSubGraph : edgesToAddToComponentsSubGraph) {
            componentsSubGraph.deleteEdge(edgeToAddToComponentSubGraph);
        }
        // Add all edges that belong to an MST to the MST
        for (Edge edgeInCurrentBlock : equalWeightEdges.keys()) {
            if (!nonCriticalEdges.contains(edgeInCurrentBlock)) {
                criticalEdges.enqueue(edgeInCurrentBlock);
            }
            vertex1 = edgeInCurrentBlock.either();
            vertex2 = edgeInCurrentBlock.other(vertex1);
            if (!unionFind.connected(vertex1, vertex2)) {
                unionFind.union(vertex1, vertex2);
                // Add edge to the minimum spanning tree
                minimumSpanningTree.enqueue(edge);
            }
        }
    }
    return criticalEdges;
}
Also used : PriorityQueueResize(chapter2.section4.PriorityQueueResize) ArrayList(java.util.ArrayList) UnionFind(chapter1.section5.UnionFind) SeparateChainingHashTable(chapter3.section4.SeparateChainingHashTable) Queue(chapter1.section3.Queue) HashSet(chapter3.section5.HashSet)

Example 5 with Queue

use of chapter1.section3.Queue in project algorithms-sedgewick-wayne by reneargento.

the class Exercise33_Certification method check.

// The order of growth of the running time of this method is O(V * E)
public boolean check(EdgeWeightedGraph edgeWeightedGraph, Queue<Edge> proposedMinimumSpanningTree) {
    // 1- Check if it is a spanning tree
    UnionFind unionFind = new UnionFind(edgeWeightedGraph.vertices());
    // O(V)
    for (Edge edge : proposedMinimumSpanningTree) {
        int vertex1 = edge.either();
        int vertex2 = edge.other(vertex1);
        if (unionFind.connected(vertex1, vertex2)) {
            // Cycle found
            return false;
        }
        unionFind.union(vertex1, vertex2);
    }
    // O(1)
    if (unionFind.count() != 1) {
        return false;
    }
    // O(V * E)
    for (Edge edgeInMST : proposedMinimumSpanningTree) {
        unionFind = new UnionFind(edgeWeightedGraph.vertices());
        // Add all edges in the MST except edgeInMST
        for (Edge edge : proposedMinimumSpanningTree) {
            if (edge != edgeInMST) {
                int vertex1 = edge.either();
                int vertex2 = edge.other(vertex1);
                unionFind.union(vertex1, vertex2);
            }
        }
        // Check that edgeInMST is the minimum-weight edge in the crossing cut
        for (Edge edge : edgeWeightedGraph.edges()) {
            int vertex1 = edge.either();
            int vertex2 = edge.other(vertex1);
            if (!unionFind.connected(vertex1, vertex2)) {
                if (edge.weight() < edgeInMST.weight()) {
                    return false;
                }
            }
        }
    }
    return true;
}
Also used : UnionFind(chapter1.section5.UnionFind)

Aggregations

In (edu.princeton.cs.algs4.In)5 Queue (edu.princeton.cs.algs4.Queue)5 Queue (chapter1.section3.Queue)4 UnionFind (chapter1.section5.UnionFind)2 HashSet (chapter3.section5.HashSet)2 Transaction (edu.princeton.cs.algs4.Transaction)2 StringJoiner (java.util.StringJoiner)2 PriorityQueueResize (chapter2.section4.PriorityQueueResize)1 SeparateChainingHashTable (chapter3.section4.SeparateChainingHashTable)1 Queue (com.jimmysun.algorithms.chapter1_3.Queue)1 Date (edu.princeton.cs.algs4.Date)1 ST (edu.princeton.cs.algs4.ST)1 StdIn (edu.princeton.cs.algs4.StdIn)1 ArrayList (java.util.ArrayList)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1