use of com.jimmysun.algorithms.chapter1_3.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");
}
use of com.jimmysun.algorithms.chapter1_3.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();
}
}
}
use of com.jimmysun.algorithms.chapter1_3.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);
}
}
}
}
use of com.jimmysun.algorithms.chapter1_3.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;
}
use of com.jimmysun.algorithms.chapter1_3.Queue in project algorithms-sedgewick-wayne by reneargento.
the class Exercise44_WebCrawler method crawlWeb.
public void crawlWeb(String sourceWebPage) {
// timeout connection after 500 milliseconds
System.setProperty("sun.net.client.defaultConnectTimeout", "500");
System.setProperty("sun.net.client.defaultReadTimeout", "1000");
Queue<String> webPagesQueue = new Queue<>();
webPagesQueue.enqueue(sourceWebPage);
HashSet<String> visited = new HashSet<>();
visited.add(sourceWebPage);
while (!webPagesQueue.isEmpty()) {
String currentWebPage = webPagesQueue.dequeue();
String webPageContent;
try {
In in = new In(currentWebPage);
webPageContent = in.readAll();
} catch (IllegalArgumentException exception) {
StdOut.println("Could not open " + currentWebPage);
continue;
}
StdOut.println(currentWebPage + " crawled");
/**
***********************************************************
* Find links of the form: http://xxx.yyy.zzz or https://xxx.yyy.zzz
* s? for either http or https
* \\w+ for one or more alpha-numeric characters
* \\. for dot
************************************************************
*/
String regexp = "http(s?)://(\\w+\\.)+(\\w+)";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(webPageContent);
// Find all matches
while (matcher.find()) {
String webPage = matcher.group();
if (!visited.contains(webPage)) {
webPagesQueue.enqueue(webPage);
visited.add(webPage);
}
}
}
}
Aggregations