Skip to content

Commit 5d65233

Browse files
Merge branch 'master' into add-sudoku-solver
2 parents f8b35c0 + 3eb521b commit 5d65233

File tree

12 files changed

+651
-8
lines changed

12 files changed

+651
-8
lines changed

pom.xml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,7 @@
7171
<artifactId>maven-compiler-plugin</artifactId>
7272
<version>3.14.1</version>
7373
<configuration>
74-
<source>21</source>
75-
<target>21</target>
74+
<release>21</release>
7675
<compilerArgs>
7776
<arg>-Xlint:all</arg>
7877
<arg>-Xlint:-auxiliaryclass</arg>
@@ -128,7 +127,7 @@
128127
<plugin>
129128
<groupId>com.mebigfatguy.fb-contrib</groupId>
130129
<artifactId>fb-contrib</artifactId>
131-
<version>7.6.14</version>
130+
<version>7.6.15</version>
132131
</plugin>
133132
<plugin>
134133
<groupId>com.h3xstream.findsecbugs</groupId>
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.thealgorithms.conversions;
2+
3+
/**
4+
* A utility class to convert between Cartesian and Polar coordinate systems.
5+
*
6+
* <p>This class provides methods to perform the following conversions:
7+
* <ul>
8+
* <li>Cartesian to Polar coordinates</li>
9+
* <li>Polar to Cartesian coordinates</li>
10+
* </ul>
11+
*
12+
* <p>The class is final and cannot be instantiated.
13+
*/
14+
public final class CoordinateConverter {
15+
16+
private CoordinateConverter() {
17+
// Prevent instantiation
18+
}
19+
20+
/**
21+
* Converts Cartesian coordinates to Polar coordinates.
22+
*
23+
* @param x the x-coordinate in the Cartesian system; must be a finite number
24+
* @param y the y-coordinate in the Cartesian system; must be a finite number
25+
* @return an array where the first element is the radius (r) and the second element is the angle (theta) in degrees
26+
* @throws IllegalArgumentException if x or y is not a finite number
27+
*/
28+
public static double[] cartesianToPolar(double x, double y) {
29+
if (!Double.isFinite(x) || !Double.isFinite(y)) {
30+
throw new IllegalArgumentException("x and y must be finite numbers.");
31+
}
32+
double r = Math.sqrt(x * x + y * y);
33+
double theta = Math.toDegrees(Math.atan2(y, x));
34+
return new double[] {r, theta};
35+
}
36+
37+
/**
38+
* Converts Polar coordinates to Cartesian coordinates.
39+
*
40+
* @param r the radius in the Polar system; must be non-negative
41+
* @param thetaDegrees the angle (theta) in degrees in the Polar system; must be a finite number
42+
* @return an array where the first element is the x-coordinate and the second element is the y-coordinate in the Cartesian system
43+
* @throws IllegalArgumentException if r is negative or thetaDegrees is not a finite number
44+
*/
45+
public static double[] polarToCartesian(double r, double thetaDegrees) {
46+
if (r < 0) {
47+
throw new IllegalArgumentException("Radius (r) must be non-negative.");
48+
}
49+
if (!Double.isFinite(thetaDegrees)) {
50+
throw new IllegalArgumentException("Theta (angle) must be a finite number.");
51+
}
52+
double theta = Math.toRadians(thetaDegrees);
53+
double x = r * Math.cos(theta);
54+
double y = r * Math.sin(theta);
55+
return new double[] {x, y};
56+
}
57+
}

src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
import java.util.Arrays;
13
/**
24
* @author Md Asif Joardar
35
*
@@ -13,11 +15,6 @@
1315
*
1416
* The time complexity of the solution is O(n × sum) and requires O(n × sum) space
1517
*/
16-
17-
package com.thealgorithms.dynamicprogramming;
18-
19-
import java.util.Arrays;
20-
2118
public final class PartitionProblem {
2219
private PartitionProblem() {
2320
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.thealgorithms.geometry;
2+
/**
3+
* This Class implements the Haversine formula to calculate the distance between two points on a sphere (like Earth) from their latitudes and longitudes.
4+
*
5+
* The Haversine formula is used in navigation and mapping to find the great-circle distance,
6+
* which is the shortest distance between two points along the surface of a sphere. It is often
7+
* used to calculate the "as the crow flies" distance between two geographical locations.
8+
*
9+
* The formula is reliable for all distances, including small ones, and avoids issues with
10+
* numerical instability that can affect other methods.
11+
*
12+
* @see "https://en.wikipedia.org/wiki/Haversine_formula" - Wikipedia
13+
*/
14+
public final class Haversine {
15+
16+
// Average radius of Earth in kilometers
17+
private static final double EARTH_RADIUS_KM = 6371.0;
18+
19+
/**
20+
* Private constructor to prevent instantiation of this utility class.
21+
*/
22+
private Haversine() {
23+
}
24+
25+
/**
26+
* Calculates the great-circle distance between two points on the earth
27+
* (specified in decimal degrees).
28+
*
29+
* @param lat1 Latitude of the first point in decimal degrees.
30+
* @param lon1 Longitude of the first point in decimal degrees.
31+
* @param lat2 Latitude of the second point in decimal degrees.
32+
* @param lon2 Longitude of the second point in decimal degrees.
33+
* @return The distance between the two points in kilometers.
34+
*/
35+
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
36+
// Convert latitude and longitude from degrees to radians
37+
double dLat = Math.toRadians(lat2 - lat1);
38+
double dLon = Math.toRadians(lon2 - lon1);
39+
40+
double lat1Rad = Math.toRadians(lat1);
41+
double lat2Rad = Math.toRadians(lat2);
42+
43+
// Apply the Haversine formula
44+
double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1Rad) * Math.cos(lat2Rad);
45+
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
46+
47+
return EARTH_RADIUS_KM * c;
48+
}
49+
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package com.thealgorithms.graph;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.Arrays;
5+
import java.util.Deque;
6+
import java.util.List;
7+
8+
/**
9+
* 0-1 BFS for shortest paths on graphs with edges weighted 0 or 1.
10+
*
11+
* <p>Time Complexity: O(V + E). Space Complexity: O(V).
12+
*
13+
* <p>References:
14+
* <ul>
15+
* <li>https://cp-algorithms.com/graph/01_bfs.html</li>
16+
* </ul>
17+
*/
18+
public final class ZeroOneBfs {
19+
20+
private ZeroOneBfs() {
21+
// Utility class; do not instantiate.
22+
}
23+
24+
/**
25+
* Computes shortest distances from {@code src} in a graph whose edges have weight 0 or 1.
26+
*
27+
* @param n the number of vertices, labeled {@code 0..n-1}
28+
* @param adj adjacency list; for each vertex u, {@code adj.get(u)} is a list of pairs
29+
* {@code (v, w)} where {@code v} is a neighbor and {@code w} is 0 or 1
30+
* @param src the source vertex
31+
* @return an array of distances; {@code Integer.MAX_VALUE} denotes unreachable
32+
* @throws IllegalArgumentException if {@code n < 0}, {@code src} is out of range,
33+
* or any edge has weight other than 0 or 1
34+
*/
35+
public static int[] shortestPaths(int n, List<List<int[]>> adj, int src) {
36+
if (n < 0 || src < 0 || src >= n) {
37+
throw new IllegalArgumentException("Invalid n or src");
38+
}
39+
int[] dist = new int[n];
40+
Arrays.fill(dist, Integer.MAX_VALUE);
41+
Deque<Integer> dq = new ArrayDeque<>();
42+
43+
dist[src] = 0;
44+
dq.addFirst(src);
45+
46+
while (!dq.isEmpty()) {
47+
int u = dq.pollFirst();
48+
List<int[]> edges = adj.get(u);
49+
if (edges == null) {
50+
continue;
51+
}
52+
for (int[] e : edges) {
53+
if (e == null || e.length < 2) {
54+
continue;
55+
}
56+
int v = e[0];
57+
int w = e[1];
58+
if (v < 0 || v >= n) {
59+
continue; // ignore bad edges
60+
}
61+
if (w != 0 && w != 1) {
62+
throw new IllegalArgumentException("Edge weight must be 0 or 1");
63+
}
64+
int nd = dist[u] + w;
65+
if (nd < dist[v]) {
66+
dist[v] = nd;
67+
if (w == 0) {
68+
dq.addFirst(v);
69+
} else {
70+
dq.addLast(v);
71+
}
72+
}
73+
}
74+
}
75+
return dist;
76+
}
77+
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
package com.thealgorithms.maths;
2+
3+
import java.math.BigInteger;
4+
import java.util.Random;
5+
6+
/**
7+
* The {@code EulerPseudoprime} class implements the Euler primality test.
8+
*
9+
* It is based on Euler’s criterion:
10+
* For an odd prime number {@code n} and any integer {@code a} coprime to {@code n}:
11+
* a^((n-1)/2) ≡ (a/n) (mod n)
12+
* where (a/n) is the Jacobi symbol.
13+
*
14+
* This algorithm is a stronger probabilistic test than Fermat’s test.
15+
* It may still incorrectly identify a composite as “probably prime” (Euler pseudoprime),
16+
* but such cases are rare.
17+
*/
18+
public final class EulerPseudoprime {
19+
20+
private EulerPseudoprime() {
21+
// Private constructor to prevent instantiation.
22+
}
23+
24+
private static final Random RANDOM = new Random(1);
25+
26+
/**
27+
* Performs the Euler primality test for a given number.
28+
*
29+
* @param n number to test (must be > 2 and odd)
30+
* @param trials number of random bases to test
31+
* @return {@code true} if {@code n} passes all Euler tests (probably prime),
32+
* {@code false} if composite.
33+
*/
34+
public static boolean isProbablePrime(BigInteger n, int trials) {
35+
if (n.compareTo(BigInteger.TWO) < 0) {
36+
return false;
37+
}
38+
if (n.equals(BigInteger.TWO) || n.equals(BigInteger.valueOf(3))) {
39+
return true;
40+
}
41+
if (n.mod(BigInteger.TWO).equals(BigInteger.ZERO)) {
42+
return false;
43+
}
44+
45+
for (int i = 0; i < trials; i++) {
46+
BigInteger a = uniformRandom(BigInteger.TWO, n.subtract(BigInteger.TWO));
47+
BigInteger jacobi = BigInteger.valueOf(jacobiSymbol(a, n));
48+
if (jacobi.equals(BigInteger.ZERO)) {
49+
return false;
50+
}
51+
52+
BigInteger exp = n.subtract(BigInteger.ONE).divide(BigInteger.TWO);
53+
BigInteger modExp = a.modPow(exp, n);
54+
55+
// Euler's criterion: a^((n-1)/2) ≡ (a/n) (mod n)
56+
if (!modExp.equals(jacobi.mod(n))) {
57+
return false; // definitely composite
58+
}
59+
}
60+
return true; // probably prime
61+
}
62+
63+
/**
64+
* Computes the Jacobi symbol (a/n).
65+
* Assumes n is positive and odd.
66+
*/
67+
public static int jacobiSymbol(BigInteger a, BigInteger n) {
68+
if (n.signum() <= 0 || n.mod(BigInteger.TWO).equals(BigInteger.ZERO)) {
69+
throw new IllegalArgumentException("n must be positive and odd.");
70+
}
71+
72+
int result = 1;
73+
a = a.mod(n);
74+
75+
while (a.compareTo(BigInteger.ZERO) != 0) {
76+
while (a.mod(BigInteger.TWO).equals(BigInteger.ZERO)) {
77+
a = a.divide(BigInteger.TWO);
78+
BigInteger nMod8 = n.mod(BigInteger.valueOf(8));
79+
if (nMod8.equals(BigInteger.valueOf(3)) || nMod8.equals(BigInteger.valueOf(5))) {
80+
result = -result;
81+
}
82+
}
83+
84+
BigInteger temp = a;
85+
a = n;
86+
n = temp;
87+
88+
if (a.mod(BigInteger.valueOf(4)).equals(BigInteger.valueOf(3)) && n.mod(BigInteger.valueOf(4)).equals(BigInteger.valueOf(3))) {
89+
result = -result;
90+
}
91+
92+
a = a.mod(n);
93+
}
94+
95+
return n.equals(BigInteger.ONE) ? result : 0;
96+
}
97+
98+
/**
99+
* Generates a random BigInteger between {@code min} and {@code max}, inclusive.
100+
*/
101+
private static BigInteger uniformRandom(BigInteger min, BigInteger max) {
102+
BigInteger result;
103+
do {
104+
result = new BigInteger(max.bitLength(), RANDOM);
105+
} while (result.compareTo(min) < 0 || result.compareTo(max) > 0);
106+
return result;
107+
}
108+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.thealgorithms.recursion;
2+
3+
import java.math.BigInteger;
4+
5+
/**
6+
* A utility class for calculating numbers in Sylvester's sequence.
7+
*
8+
* <p>Sylvester's sequence is a sequence of integers where each term is calculated
9+
* using the formula:
10+
* <pre>
11+
* a(n) = a(n-1) * (a(n-1) - 1) + 1
12+
* </pre>
13+
* with the first term being 2.
14+
*
15+
* <p>This class is final and cannot be instantiated.
16+
*
17+
* @see <a href="https://en.wikipedia.org/wiki/Sylvester_sequence">Wikipedia: Sylvester sequence</a>
18+
*/
19+
public final class SylvesterSequence {
20+
21+
// Private constructor to prevent instantiation
22+
private SylvesterSequence() {
23+
}
24+
25+
/**
26+
* Calculates the nth number in Sylvester's sequence.
27+
*
28+
* <p>The sequence is defined recursively, with the first term being 2:
29+
* <pre>
30+
* a(1) = 2
31+
* a(n) = a(n-1) * (a(n-1) - 1) + 1 for n > 1
32+
* </pre>
33+
*
34+
* @param n the position in the sequence (must be greater than 0)
35+
* @return the nth number in Sylvester's sequence
36+
* @throws IllegalArgumentException if n is less than or equal to 0
37+
*/
38+
public static BigInteger sylvester(int n) {
39+
if (n <= 0) {
40+
throw new IllegalArgumentException("sylvester() does not accept negative numbers or zero.");
41+
}
42+
if (n == 1) {
43+
return BigInteger.valueOf(2);
44+
} else {
45+
BigInteger prev = sylvester(n - 1);
46+
// Sylvester sequence formula: a(n) = a(n-1) * (a(n-1) - 1) + 1
47+
return prev.multiply(prev.subtract(BigInteger.ONE)).add(BigInteger.ONE);
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)