text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_prefix|>package com.williamfiset.algorithms.dp;
// Simple interface for MinimumWeightPerfectMatching (MWP<|fim_suffix|>matching cost
public double getMinWeightCost();
// Returns an optimal matching.
public int[] getMatching();
}
<|fim_middle|>M) solutions to simplify testing.
public interface MwpmInterfac... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Implementation of the Minimum Weight Perfect Matching (MWPM) problem. In this problem you are
* given a distance matrix which gives the distance from each node to every other node, and you want
* to pair up all the nodes to one another minimizing the overall cost.
*
* <p>Tested against: UVA 109... | fim | williamfiset/algorithms | java |
<|fim_suffix|>icial node in the end.
private void setCostMatrix(Double[][] inputMatrix) {
isOdd = (n % 2 == 0) ? false : true;
Double[][] newCostMatrix = null;
if (isOdd) {
newCostMatrix = new Double[n + 1][n + 1];
} else {
newCostMatrix = new Double[n][n];
}
for (int i = 0; i < ... | fim | williamfiset/algorithms | java |
<|fim_suffix|>("f(%d) = %d (recursive soln)\n", i, solver.recursiveSolution(i));
}
// long startTime = System.currentTimeMillis();
// int n = 60000000;
// int[] tiles = {100000, 10000000, 20000000, 30000000};
// System.out.println(f(n, tiles));
// long endTime = System.currentTimeMillis();
... | fim | williamfiset/algorithms | java |
<|fim_prefix|>package com.williamfiset.algorithms.dp.examples.d<|fim_suffix|> int state = makeState(t1, t2);
if (dp[i][state] != null) {
return dp[i][state];
}
// Zones that define which regions are free. For the surrounding 4 tiles:
// t1 t3
// t2 t4
boolean t3 = i + 1 < n;
boolean ... | fim | williamfiset/algorithms | java |
<|fim_suffix|>stance to transform `a` into `b`
public int editDistance() {
Integer[][] dp = new Integer[a.length + 1][b.length + 1];
return f(dp, 0, 0);
}
private int f(Integer[][] dp, int i, int j) {
if (i == a.length && j == b.length) {
return 0;
}
if (i == a.length) {
return (b... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Problem: https://leetcode.com/problems/house-robber
*
* <p>Time Complexity: O(n), space Complexity: O(n)
*
* <p>Download the code: $ git clone https://github.com/williamfiset/Algorithms
*
* <p>Change directory to the root of the Algorithms directory:
*
* <p>$ cd Algorithms
*
* <p>Build: $... | fim | williamfiset/algorithms | java |
<|fim_suffix|>alCows {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// The maximum number of days.
static final int MAX_DAYS = 50;
public static void main(String[] args) throws IOException {
String[] line = br.readLine().split(" ");
// The maximum number of cows o... | fim | williamfiset/algorithms | java |
package com.williamfiset.algorithms.dp.examples.narrowartgallery;
/**
* Solution to the Narrow Art Gallery problem from the 2014 ICPC North America Qualifier
*
* <p>Problem: https://open.kattis.com/problems/narrowartgallery
*
* <p>Problem Author: Robert Hochberg
*
* <p>Solution by: William Fiset
*/
import java... | fim | williamfiset/algorithms | java |
<|fim_prefix|>package com.williamfiset.algorithms.dp.examples.scenes;
/**
* Solution to the Mountain Scenes problem (https://open.kattis.com/problems/scenes)
*
* <p>Solution by: William Fiset
*/
import java.io.*;
public class Scenes {
static Long[][] dp;
static int N, <|fim_suffix|>ying the MOD after the loo... | fim | williamfiset/algorithms | java |
<|fim_prefix|>package com.williamfiset.algorithms.dp.examples.tilingdominoes;
/**
* Solution to Tri Tiling (https://open.kattis.com/problems/tritiling)
*
* <p>Explanation video: https://www.youtube.com/watch?v=yn2jnmlepY8
*
* <p>Solution by: William Fiset
*/
import java.util.*;
public class TilingDominoes {
s... | fim | williamfiset/algorithms | java |
/**
* This file shows you how to find the smaller of the two angles between two vectors in R2
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.geometry;
import static java.lang.Math.*;
public class AngleBetweenVectors2D {
// Retu... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* This file shows you how to find the smaller of the two angles between two vectors in R3
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.geometry;
import<|fim_suffix|>1z, double v2x, double v2y, double v2z) {
... | fim | williamfiset/algorithms | java |
<|fim_suffix|>nts are returned where the intersection is.
public static Point2D[] circleCircleIntersection(Point2D c1, double r1, Point2D c2, double r2) {
// r is the smaller radius and R is bigger radius
double r, R;
// c is the center of the small circle
// C is the center of the big circle
Po... | fim | williamfiset/algorithms | java |
// See live demo:
// http://www.williamfiset.com/circlecircleintersection
// Let EPS (epsilon) be a small value
var EPS = 0.0000001;
// Let a point be a pair: (x, y)
function Point(x, y) {
this.x = x;
this.y = y;
}
// Define a circle centered at (x,y) with radius r
function Circle(x,y,r) {
this.x = x;
this.y... | fim | williamfiset/algorithms | javascript |
<|fim_prefix|>/**
* This file shows you how to find the area of a circular segment which lies on the circumference of
* a circle of radius r.
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.wi<|fim_suffix|> // Let v1 = <bx-ax, by-ay> and v2 = <cx-ax, cy-a... | fim | williamfiset/algorithms | java |
<|fim_suffix|> double dist = nextPoint.dist(next);
if (dist < d) {
pt1 = nextPoint;
pt2 = next;
d = dist;
}
next = yWorkingSet.lower(next);
}
// Duplicate/stacked points
if (yWorkingSet.contains(nextPoint)) {
pt1 = pt2 = nextPoint;
... | fim | williamfiset/algorithms | java |
/**
* In this file I show you how to determine if three points are collinear to each other (on the same
* line).
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.geometry;
import static java.lang.Math.*;
import java.awt.geom.Point2... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* A working implementation of the GrahamScan convex hull algorithm
*
* <p>Time Complexity: O(nlogn)
*
* @author Micah Stairs, William Fiset
*/
package com.williamfiset.algorithms.geometry;
import java.awt.geom.Point2D;
import java.util.*;
public class ConvexHullGrahamScan {
// Construct a c... | fim | williamfiset/algorithms | java |
/**
* "[Andrew, 1979] discovered an alternative to the Graham scan that uses a linear lexicographic
* sort of the point set by the x and y-coordinates. This is an advantage if this ordering is
* already known for a set, which is sometimes the case. But even if sorting is required, this is a
* faster sort than the a... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* This file contains code that can find the area of a convex polygon if the points are given in CW
* or CCW order.
*
* <p>Time Complexity: O(n)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.geometry;
import java.awt.geom.Point2D;
public cl... | fim | williamfiset/algorithms | java |
<|fim_suffix|>inear(p0, hull[hi], p) >= 0) lo = hi;
else hi = lo;
}
}
Point2D p1 = hull[lo], p2 = hull[lo + 1];
double boundSign = collinear(p1, p2, p);
double segSign1 = collinear(p0, p1, p);
double segSign2 = collinear(p0, p2, p);
return (boundSign >= 0 && segSign1 >= 0 && segS... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* This algorithm cuts a ordered convex polygon with a line segment and returns the two resulting
* pieces.
*
* <p>Time Complexity: O(nlogn)
*
* @author Finn Lidbetter
*/
package com.williamfiset.al<|fim_suffix|> the line
// will return the other part of the polygon).
public static Pt[] cut(... | fim | williamfiset/algorithms | java |
<|fim_suffix|>e dot product of two vectors is zero
// then they are orthogonal!)
//
// First, consider the three vectors spanning outwards from say point 'a':
// v1 = b-a, v2 = c-a, and v3 = d-a. If we take the cross product of any
// of these vectors (say v1 and v2) then we can obtain a fourth vect... | fim | williamfiset/algorithms | java |
<|fim_suffix|>tatic Line slopePointToLine(double slope, Point2D pt) {
Point2D p2 = null;
if (slope == Double.POSITIVE_INFINITY || slope == Double.NEGATIVE_INFINITY) {
p2 = new Point2D.Double(pt.getX(), pt.getY() + 1);
} else {
p2 = new Point2D.Double(pt.getX() + 1, pt.getY() + slope);
}
... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Find the intersection of a line in general form with a circle See live demo:
* http://www.williamfiset.com/circlelineintersection
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.geometry;
import static java.lang... | fim | williamfiset/algorithms | java |
<|fim_suffix|> + (b^2X^2 + b^2Y^2 - 2bcY + c^2 - b^2r^2) = 0
var A = a*a + b*b;
var B = 2*a*b*y - 2*a*c - 2*b*b*x;
var C = b*b*x*x + b*b*y*y - 2*b*c*y + c*c - b*b*r*r;
// Use quadratic formula x = (-b +- sqrt(a^2 - 4ac))/2a to find the
// roots of the equation (if they exist).
var D = B*B - 4*A*C;
... | fim | williamfiset/algorithms | javascript |
<|fim_prefix|>// See live demo:
// http://www.williamfiset.com/linesegmentcircleintersection
// Small epsilon value
var EPS = 0.0000001;
// point (x, y)
function Point(x, y) {
this.x = x;
this.y = y;
}
// Circle with center at (x,y) and radius r
function Circle(x, y, r) {
this.x = x;
this.y = y;
this.r = r... | fim | williamfiset/algorithms | javascript |
<|fim_suffix|>
if (p1.equals(p3)) {
points.add(p1);
if (p2.equals(p4)) points.add(p2);
} else if (p1.equals(p4)) {
points.add(p1);
if (p2.equals(p3)) points.add(p2);
} else if (p2.equals(p3)) {
points.add(p2);
if (p1.equals(p4)) points.add(p1);
} else if (p2.equals... | fim | williamfiset/algorithms | java |
<|fim_suffix|> }
// Example converting to general form
public static void main(String[] args) {
// The line segment (1, 1), (3, -4) gives the
// line _x + _y + _ = 0 in general form
double[] abc = segmentToGeneralForm(1, 1, 3, -4);
System.out.printf("%.2fx + %.2fy + %.2f = 0\n", abc[0], abc[1], ab... | fim | williamfiset/algorithms | java |
/**
* This file shows you how to find the distance between two geographic coordinates.
*
* <p>Time Complexity: O(1)
*
* @author Micah Stairs
*/
package com.williamfiset.algorithms.geometry;
import static java.lang.Math.*;
public class LongitudeLatitudeGeographicDistance {
// Compute the distance between geog... | fim | williamfiset/algorithms | java |
<|fim_suffix|>[j + i], polygon[k]));
}
}
}
return dp[0][len - 1];
}
}
<|fim_prefix|>/**
* This file shows you how to find the minimum cost convex polygon triangulation of a set of points.
* Points must be in either clockwise or counterclockwise order.
*
* <p>Time Complexity: O(n^3)
*
* @au... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Given a circle and a point around or inside the circle we wish to find place(s) of intersection
* of the lines from the point which are tangent to the circle. For an animation see here:
* http://jsfiddle.net/zxqCw/1/
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, william.alexandre.fi... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* This file shows you how to determine if a point is inside or on the boundary of a triangle formed
* by three points.
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.geometry;
import static java.lang.Math.*;
imp... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* This file shows you how to rotate a point clockwise relative to a fixed point a certain number of
* radians.
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.geometry;
import static java.lang.Math.*;
import java... | fim | williamfiset/algorithms | java |
<|fim_suffix|>
System.out.println(triangleArea(a, b, c));
double side1 = a.distance(b);
double side2 = a.distance(c);
double side3 = b.distance(c);
System.out.println(triangleArea(side1, side2, side3));
}
}
<|fim_prefix|>/**
* There is more than one way to take the area of a triangle, some are... | fim | williamfiset/algorithms | java |
<|fim_suffix|>< EPS) {
if (Math.abs(h - other.h) < EPS) return 0;
return (h - other.h) > 0 ? +1 : -1;
}
return (f - other.f) > 0 ? +1 : -1;
}
}
// Run A* algorithm on a directed graph to find the shortest path
// from a starting node to an ending node. If there is no path between ... | fim | williamfiset/algorithms | java |
<|fim_suffix|> (int i = 0; i < n; i++)
if (isArticulationPoint[i]) System.out.printf("Node %d is an articulation\n", i);
}
//
// 0 --- 1 --- 2
//
// Articulation point: 1
//
private static void testExample2() {
int n = 3;
List<List<Integer>> graph = createGraph(n);
addEdge(graph, 0, 1... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* An implementation of the Bellman-Ford algorithm. The algorithm finds the shortest path between a
* starting node and all other nodes in the graph. The algorithm also detects negative cycles.
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.grap... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* An implementation of the Bellman-Ford algorithm. The algorithm finds the shortest path between a
* starting node and all other nodes in the graph. The algorithm also detects negative cycles.
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.grap... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Boruvka's Minimum Spanning Tree Algorithm — Edge List
*
* <p>Finds the MST of a weighted undirected graph by repeatedly selecting the
* cheapest outgoing edge from each connected component and merging components.
*
* <p>Algorithm:
* <ol>
* <li>Start with each node as its own component (usi... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Breadth-First Search (BFS) — Adjacency List
*
* <p>Explores a graph level by level outward from a starting node using a
* FIFO queue. Because BFS visits nodes in order of increasing distance,
* it naturally finds the shortest path (fewest edges) between two nodes
* in an unweighted graph.
*
... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Bridge Edges (Cut Edges) — Adjacency List
*
* <p>A bridge is an edge whose removal disconnects the graph (or increases
* the number of connected components). This implementation uses Tarjan's
* DFS-based algorithm with low-link values.
*
* <p>An edge (u, v) is a bridge if no vertex in the sub... | fim | williamfiset/algorithms | java |
/**
* This file is still a WIP
*
* <p>Still need to: - Implemented undirected edge eulerain path algo
*
* <p>bazel run //src/main/java/com/williamfiset/algorithms/graphtheory:ChinesePostmanProblem
*/
package com.williamfiset.algorithms.graphtheory;
import java.util.*;
public class ChinesePostmanProblem {
// ... | fim | williamfiset/algorithms | java |
/**
* Connected Components — Adjacency List (DFS)
*
* <p>Finds all connected components of an undirected graph using depth-first
* search. Each unvisited node starts a new DFS that labels every reachable node
* with the same component id.
*
* <p>For directed graphs, use Tarjan's or Kosaraju's algorithm to find
... | fim | williamfiset/algorithms | java |
<|fim_suffix|>ic ConnectedComponentsUnionFind(List<List<Integer>> graph) {
if (graph == null) {
throw new IllegalArgumentException();
}
this.n = graph.size();
this.graph = graph;
}
/**
* Returns the number of connected components.
*/
public int countComponents() {
solve();
ret... | fim | williamfiset/algorithms | java |
/**
* Depth-First Search — Adjacency List (Recursive)
*
* <p>Performs a recursive DFS traversal on a directed graph represented as an
* adjacency list, counting the number of reachable nodes from a given source.
*
* <p>Time: O(V + E)
* <p>Space: O(V)
*
* @author William Fiset, william.alexandre.fiset@gmail.co... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* This file contains an implementation of <|fim_suffix|>e directed edge starts at.
* @param to - The index of the node the directed edge ends at.
* @param cost - The cost of the edge.
*/
public void addEdge(int from, int to, int cost) {
graph.get(from).add(new Edge(from, to, cost));
... | fim | williamfiset/algorithms | java |
<|fim_suffix|>index = i = j;
return index;
}
private void swap(int i, int j) {
pm[im[j]] = i;
pm[im[i]] = j;
int tmp = im[i];
im[i] = im[j];
im[j] = tmp;
}
// Tests if the value of node i < node j
@SuppressWarnings("unchecked")
private boolean less(int i, in... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Eager implementation of Prim's minimum spanning tree algorithm using an indexed priority queue
* (IPQ).
*
* <p>"Eager" because when a better edge to a frontier node is found, the IPQ entry is updated
* in-place (via {@code decrease}), so stale edges never accumulate — unlike the lazy variant wh... | fim | williamfiset/algorithms | java |
<|fim_suffix|>djacencyList solver = new EulerianPathDirectedEdgesAdjacencyList(graph);
// Expected path: [1, 3, 5, 6, 3, 2, 4, 3, 1, 2, 2, 4, 6]
int[] path = solver.getEulerianPath();
System.out.println("Path from slides: " + Arrays.toString(path));
}
private static void smallExample() {
int n = 5... | fim | williamfiset/algorithms | java |
<|fim_suffix|> degree[e.u]++;
// Because edges have duplicate refs in the graph skip the opposing edge.
e.used = true;
edgeCount++;
}
}
resetUsed(graph);
}
private boolean graphHasEulerianPath() {
int oddNodes = 0;
for (int i = 0; i < n; i++) {
if (degree[i... | fim | williamfiset/algorithms | java |
<|fim_suffix|>l || matrix.length == 0)
throw new IllegalArgumentException("Matrix cannot be null or empty.");
n = matrix.length;
dp = new double[n][n];
next = new Integer[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] != POSITIVE_INFINITY)
... | fim | williamfiset/algorithms | java |
<|fim_suffix|>DirectedEdge(g, 1, 2);
addDirectedEdge(g, 1, 3);
addDirectedEdge(g, 2, 3);
addDirectedEdge(g, 2, 4);
addDirectedEdge(g, 3, 4);
addDirectedEdge(g, 5, 4);
Kahns solver = new Kahns();
System.out.println(java.util.Arrays.toString(solver.kahns(g)));
}
private static void cycleT... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Implementation of Kosaraju's SCC algorithm
*
* <p>Verified against:
*
* <ul>
* <li>https://open.kattis.com/problems/equivalences
* <li>https://open.kattis.com/problems/runningmom
* </ul>
*
* <p>bazel run //src/main/java/com/williamfiset/algorithms/graphtheory:Kosaraju
*/
package com.w... | fim | williamfiset/algorithms | java |
<|fim_suffix|>nimum Spanning Tree (MST) cost if there exists
// a MST, otherwise it returns null.
static Long kruskals(Edge[] edges, int n) {
if (edges == null) return null;
long sum = 0L;
java.util.Arrays.sort(edges);
UnionFind uf = new UnionFind(n);
for (Edge edge : edges) {
// Skip ... | fim | williamfiset/algorithms | java |
/**
* Lazy implementation of Prim's minimum spanning tree algorithm using a priority queue.
*
* <p>"Lazy" because stale edges (to already-visited nodes) remain in the priority queue and are
* skipped when polled, rather than being eagerly removed or updated.
*
* <p>Time: O(E log(E))
*
* <p>Space: O(V + E)
*
*... | fim | williamfiset/algorithms | java |
/**
* This file contains an implementation of a Steiner Tree algorithm, which finds the cheapest cost
* to connect a given subset of nodes (which we will refer to as terminal nodes) in an undirected
* graph. These nodes may be either directly or indirectly connected, possibly connecting to
* intermediate nodes whic... | fim | williamfiset/algorithms | java |
<|fim_suffix|>t.printf("Number of Strongly Connected Components: %d\n", solver.sccCount());
for (List<Integer> scc : multimap.values()) {
System.out.println("Nodes: " + scc + " form a Strongly Connected Component.");
}
}
}
<|fim_prefix|>/**
* Implementation of Tarjan's Strongly Connected Components alg... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Topological sort implementation using DFS on an adj<|fim_suffix|>st())) {
int newDist = dist[nodeIndex] + edge.weight;
if (dist[edge.to] == null || newDist < dist[edge.to])
dist[edge.to] = newDist;
}
}
return dist;
}
public static void main(String[] arg... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* This file shows you how to solve the traveling salesman problem using a brute force approach.
* Since the time complexity is on the order of O(n!) this method is not convenient for n > 12
*
* <p>Time Complexity: O(n!)
*
* @author William Fiset, Micah Stairs
*/
package com.williamfiset.algorit... | fim | williamfiset/algorithms | java |
<|fim_prefix|>package com.williamfiset.algorithms.graphtheory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Traveling Salesman Problem — Iterative DP with Bitmask
*
* Given a complete weighted graph of n nodes, find the minimum-cost
* Hamiltonian cycle (a tour that visits... | fim | williamfiset/algorithms | java |
<|fim_suffix|>ceMatrix[3][0] = distanceMatrix[0][3] = 8;
distanceMatrix[0][5] = distanceMatrix[5][0] = 10;
distanceMatrix[5][1] = distanceMatrix[1][5] = 12;
// Run the solver
TspDynamicProgrammingRecursive solver = new TspDynamicProgrammingRecursive(distanceMatrix);
// Prints: [0, 3, 2, 4, 1, 5, 0... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/** NOTE: This file is still in development! */
package com.williamfiset.algorithms.graphtheory;
import java.util.*;
public class TwoSatSolverAdjacencyList {
private int n;
private List<List<Integer>> graph;
private boolean solved;
private boolean isSatisfiable;
private TarjanSccSolverAdjace... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/*
Performs density analysis to figure out whether an adjacency list or an
adjacency matrix is better for prims MST algorithm.
Results seem to indicate that the adjacency matrix is better starting at
around ~33% edge percentage density:
Percentage full: ~0%, Edges included: 0
List: 1168811 nanos
Matri... | fim | williamfiset/algorithms | java |
<|fim_suffix|>ues[ki], value)) {
values[ki] = value;
sink(pm[ki]);
}
}
/* Helper functions */
private void sink(int i) {
for (int j = minChild(i); j != -1; ) {
swap(i, j);
i = j;
j = minChild(i);
}
}
private void swim(int i) {
while ... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Bipartite Graph Check — Adjacency List (DFS coloring)
*
* Determines if an undirected graph is bipartite (2-colorable) by attempting
* to color it with two colors via DFS. A graph is bipartite if and only if
* it contains no odd-length cycles.
*
* The algorithm starts a DFS from node 0, alter... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Implementation of the Capacity Scaling algorithm using a DFS as a method of finding augmenting
* paths.
*
* <p>Time Complexity: O(E^2log(U)), where E = num edges, U = max capacity
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.graphtheory.n... | fim | williamfiset/algorithms | java |
/**
* Implementation of Dinic's network flow algorithm. The algorithm works by first constructing a
* level graph using a BFS and then finding augmenting paths on the level graph using multiple DFSs.
*
* <p>Run script:
*
* <p>$ bazel run //src/main/java/com/williamfiset/algorithms/graphtheory/networkflow:Dinics
... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* An implementation of the Edmonds-Karp algorithm which is essentially Ford-Fulkerson with a BFS as
* a method of finding augmenting paths. This Edmonds-Karp algorithm will allow you to find the max
* flow through a directed graph and the min cut as a byproduct.
*
* <p>Time Complexity: O(VE^2)
*... | fim | williamfiset/algorithms | java |
<|fim_suffix|>ength; i++) {
if (visited[i] != visitedToken && cap[i] > 0) {
if (cap[i] < flow) flow = cap[i];
int dfsFlow = dfs(caps, visited, i, sink, flow);
if (dfsFlow > 0) {
caps[node][i] -= dfsFlow;
caps[i][node] += dfsFlow;
return dfsFlow;
}
... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Ford-Fu<|fim_suffix|>ic void solve() {
// Repeatedly find augmenting paths via DFS and accumulate flow.
for (long f = dfs(s, INF); f != 0; f = dfs(s, INF)) {
markAllNodesAsUnvisited();
maxFlow += f;
}
// Nodes still reachable from source in the residual graph form the m... | fim | williamfiset/algorithms | java |
<|fim_suffix|>nt oppositeNode = next[node];
if (oppositeNode == FREE) {
// Record which node we came from and return
// 1 to indicate a path was found
next[node] = at;
return 1;
}
// We were able to find an alternating path
if (augment(graph, visited, next, oppo... | fim | williamfiset/algorithms | java |
<|fim_suffix|>(VE)
for (int i = 0; i < n - 1; i++)
for (List<Edge> edges : graph)
for (Edge edge : edges)
if (edge.remainingCapacity() > 0 && dist[edge.from] + edge.cost < dist[edge.to])
dist[edge.to] = dist[edge.from] + edge.cost;
adjustEdgeCosts(dist);
}
// Adjust edg... | fim | williamfiset/algorithms | java |
<|fim_suffix|>
MinCostMaxFlowWithBellmanFord solver;
solver = new MinCostMaxFlowWithBellmanFord(n, s, t);
solver.addEdge(s, 1, 4, 10);
solver.addEdge(s, 2, 2, 30);
solver.addEdge(1, 2, 2, 10);
solver.addEdge(1, t, 0, 9999);
solver.addEdge(2, t, 4, 10);
// Prints: Max flow: 4, Min cost:... | fim | williamfiset/algorithms | java |
/**
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.graphtheory.networkflow;
import java.util.ArrayList;
import java.util.List;
public abstract class NetworkFlowSolverBase {
// To avoid overflow, set infinity to a value less than Long.MAX_VALUE;
protected stati... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* An implementation the Ford-Fulkerson method with a DFS using capacity scaling to find the maximum
* flow of a flow graph.
*
* <p>Time Complexity: O(E^2log(U)), where E is the number of edges and U is the maximum capacity
* value in the initial flow graph.
*
* <p>Download the code: $ git clone... | fim | williamfiset/algorithms | java |
<|fim_suffix|>low() {
execute();
return maxFlow;
}
// Wrapper method that ensures we only call solve() once
private void execute() {
if (solved) return;
solved = true;
solve();
}
// Method to implement which solves the network flow problem.
public abstract void so... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* An implementation of the Edmonds-Karp algorithm to find the maximum flow.
*
* <p>Time Complexity: O(VE^2), where v is the number of vertices and E is the number of edges.
*
* <p>Download the code: $ git clone https://github.com/williamfiset/Algorithms
*
* <p>Change directory to the root of th... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* An implementation of the Ford-Fulkerson (FF) method with a DFS as a method of finding augmenting
* paths.
*
* <p>Time Complexity: O(fE), where f is the max flow and E is the number of edges
*
* <p>Download the code: $ git clone https://github.com/williamfiset/Algorithms
*
* <p>Change directo... | fim | williamfiset/algorithms | java |
<|fim_suffix|>r of nodes in the graph including s and t.
* @param s - The index of the source node, 0 <= s < n
* @param t - The index of the sink node, 0 <= t < n and t != s
*/
public NetworkFlowSolverBase(int n, int s, int t) {
this.n = n;
this.s = s;
this.t = t;
initializeEm... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Implementation of finding the Lowest Common Ancestor (LCA) of a tree. This impl first finds an
* Euler tour from the root node which visits all the nodes in the tree. The node height values
* obtained from the Euler tour can then be used in combination with a sparse table to find the LCA
* in O(... | fim | williamfiset/algorithms | java |
<|fim_suffix|> }
public static void addUndirectedEdge(List<List<Integer>> graph, int from, int to) {
graph.get(from).add(to);
graph.get(to).add(from);
}
// ==================== Main ====================
public static void main(String[] args) {
// Undirected tree:
//
// 0 - 1 - 2 - 3 - ... | fim | williamfiset/algorithms | java |
<|fim_suffix|>- 1 - 2 - 3 - 4
// | |
// 6 5
// / \
// 7 8
//
// Center: [2]
List<List<Integer>> graph = createEmptyTree(9);
addUndirectedEdge(graph, 0, 1);
addUndirectedEdge(graph, 2, 1);
addUndirectedEdge(graph, 2, 3);
addUndirected... | fim | williamfiset/algorithms | java |
<|fim_suffix|>ndirectedEdge(graph5, 1, 2);
addUndirectedEdge(graph5, 2, 3);
System.out.println(findTreeCenters(graph5));
// Centers are 2,3
List<List<Integer>> graph6 = createEmptyTree(7);
addUndirectedEdge(graph6, 0, 1);
addUndirectedEdge(graph6, 1, 2);
addUndirectedEdge(graph6, 2, 3);
... | fim | williamfiset/algorithms | java |
<|fim_suffix|> addUndirectedEdge(graph, 2, 3);
addUndirectedEdge(graph, 2, 4);
addUndirectedEdge(graph, 4, 5);
addUndirectedEdge(graph, 4, 6);
addUndirectedEdge(graph, 6, 7);
addUndirectedEdge(graph, 6, 9);
addUndirectedEdge(graph, 7, 8);
diameter = treeDiameter(graph, 5);
System.out... | fim | williamfiset/algorithms | java |
<|fim_suffix|>helpers */
public static List<List<Integer>> createEmptyGraph(int n) {
List<List<Integer>> graph = new ArrayList<>(n);
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
return graph;
}
public static void addUndirectedEdge(List<List<Integer>> graph, int from, int to) {
graph... | fim | williamfiset/algorithms | java |
<|fim_prefix|>/**
* Tree height example
*
* <p>Download the code: <br>
* $ git clone https://github.com/williamfiset/Algorithms
*
* <p>Run: <br>
* $ bazel run //src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/examples:TreeHeight
*
* <p>Time Complexity: O(n)
*
* @author William Fiset, wil... | fim | williamfiset/algorithms | java |
/**
* Tree sum example
*
* <p>Download the code: <br>
* $ git clone https://github.com/williamfiset/Algorithms
*
* <p>Run: <br>
* $ bazel run //src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/examples:TreeSum
*
* <p>Time Complexity: O(n)
*
* @author William Fiset, william.alexandre.fiset... | fim | williamfiset/algorithms | java |
<|fim_suffix|>| B[0].length != n || C.length != n || C[0].length != n)
throw new IllegalArgumentException("Input must be three nxn matrices");
int[] v = new int[n];
for (int trial = 0; trial < k; trial++) {
randomizeVector(v);
// Compare C*v against A*(B*v) — both are O(n^2) matrix-vector pr... | fim | williamfiset/algorithms | java |
<|fim_suffix|>olutions(augmentedMatrix) && !isInconsistent(augmentedMatrix)) {
double x = augmentedMatrix[0][3];
double y = augmentedMatrix[1][3];
double z = augmentedMatrix[2][3];
// x ~ 3.755, y ~ 10.531, z ~ 6.816
System.out.printf("x = %.3f, y = %.3f, z = %.3f\n", x, y, z);
}
}
}... | fim | williamfiset/algorithms | java |
<|fim_suffix|>rence: f(n) = 0 + 1*f(n-1) + 1*f(n-2)
long[] coefficients = {1, 1};
long k = 0;
for (int i = 0; i <= 10; i++) {
long fib = solveRecurrence(coefficients, 1, k, i);
System.out.println(fib);
}
// Suppose we have the following recurrence:
// f(n) = 2 + 2f(n-1) + f(n-3) wi... | fim | williamfiset/algorithms | java |
<|fim_suffix|> {-8, 10, 8, 3, 2},
{5, 5, 5, 5, 5}
};
System.out.println(determinant(m)); // -27435
m =
new double[][] {
{1, 3, 5, 9},
{1, 3, 1, 7},
{4, 3, 9, 7},
{5, 2, 0, 9},
}; // determinant(mat1) = -376 , mat(4 * 4)
System.out.... | fim | williamfiset/algorithms | java |
<|fim_suffix|> (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
inv[i][j] = augmented[i][j + n];
return inv;
}
/** Reduces an augmented matrix to RREF in-place. */
private static void solve(double[][] augmentedMatrix) {
int nRows = augmentedMatrix.length, nCols = augmentedMatrix[0].lengt... | fim | williamfiset/algorithms | java |
<|fim_prefix|>package com.williamfiset.algorithms.linearalgebra;
import java.util.Arrays;
/**
* Standard Matrix Multiplication
*
* Computes the product C = A * B using the naive triple-loop algorithm.
* Matrix A has dimensions (aRows x aCols) and B has (bRows x bCols);
* multiplication i<|fim_suffix|>: O(n^3) f... | fim | williamfiset/algorithms | java |
<|fim_suffix|>println(Arrays.toString(m));
System.out.println();
}
}
<|fim_prefix|>package com.williamfiset.algorithms.linearalgebra;
import java.util.Arrays;
/**
* Matrix Exponentiation (Binary Exponentiation)
*
* Raises an n x n square matrix to the power p using repeated squaring
* (binary exponentiation... | fim | williamfiset/algorithms | java |
<|fim_suffix|> {
if (arr.length != arr[0].length) return null;
int n = arr.length;
// Build augmented matrix [A | I]
int[][] augmented = new int[n][n * 2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
augmented[i][j] = arr[i][j];
augmented[i][i + n] = 1;
}
r... | fim | williamfiset/algorithms | java |
<|fim_suffix|>1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
rotate(matrix);
for (int[] row : matrix)
System.out.println(Arrays.toString(row));
// prints:
// [21, 16, 11, 6, 1]
// [22, 17, 12, 7, 2]
// [23,... | fim | williamfiset/algorithms | java |
<|fim_suffix|>int i = 0; i < m.length; i++) {
if (i != r) {
v = m[i][c];
for (int j = 0; j < m[i].length; j++)
m[i][j] -= m[r][j] * v;
}
}
}
return m[0][0];
}
}
<|fim_prefix|>package com.williamfiset.algorithms.linearalgebra;
/**
* Simplex Algorithm for ... | fim | williamfiset/algorithms | java |
<|fim_suffix|>out of range.
*/
public static long compute(int n, int r, int p) {
if (n < 0 || r < 0 || r > n)
throw new IllegalArgumentException("Requires 0 <= r <= n, got n=" + n + ", r=" + r);
if (p <= 1)
throw new IllegalArgumentException("Modulus p must be > 1, got p=" + p);
if (r == 0... | fim | williamfiset/algorithms | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.