Skip to content

Commit b13cd3a

Browse files
authored
Merge branch 'master' into added-mos-algorithm-dice-thrower
2 parents c7a0406 + 9484c7e commit b13cd3a

7 files changed

Lines changed: 301 additions & 2 deletions

File tree

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: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.thealgorithms.dynamicprogramming;
2-
32
import java.util.Arrays;
4-
53
/**
64
* @author Md Asif Joardar
75
*
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: 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+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.conversions;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.CsvSource;
8+
9+
public class CoordinateConverterTest {
10+
11+
@ParameterizedTest
12+
@CsvSource({"0, 0, 0, 0", "1, 0, 1, 0", "0, 1, 1, 90", "-1, 0, 1, 180", "0, -1, 1, -90", "3, 4, 5, 53.13010235415599"})
13+
void testCartesianToPolar(double x, double y, double expectedR, double expectedTheta) {
14+
assertArrayEquals(new double[] {expectedR, expectedTheta}, CoordinateConverter.cartesianToPolar(x, y), 1e-9);
15+
}
16+
17+
@ParameterizedTest
18+
@CsvSource({"1, 0, 1, 0", "1, 90, 0, 1", "1, 180, -1, 0", "1, -90, 0, -1", "5, 53.13010235415599, 3, 4"})
19+
void testPolarToCartesian(double r, double theta, double expectedX, double expectedY) {
20+
assertArrayEquals(new double[] {expectedX, expectedY}, CoordinateConverter.polarToCartesian(r, theta), 1e-9);
21+
}
22+
23+
@ParameterizedTest
24+
@CsvSource({"NaN, 1", "1, NaN", "Infinity, 1", "1, Infinity", "-Infinity, 1", "1, -Infinity"})
25+
void testCartesianToPolarInvalidInputs(double x, double y) {
26+
assertThrows(IllegalArgumentException.class, () -> CoordinateConverter.cartesianToPolar(x, y));
27+
}
28+
29+
@ParameterizedTest
30+
@CsvSource({"-1, 0", "1, NaN", "1, Infinity", "1, -Infinity"})
31+
void testPolarToCartesianInvalidInputs(double r, double theta) {
32+
assertThrows(IllegalArgumentException.class, () -> CoordinateConverter.polarToCartesian(r, theta));
33+
}
34+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.thealgorithms.geometry;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.stream.Stream;
6+
import org.junit.jupiter.api.DisplayName;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.Arguments;
9+
import org.junit.jupiter.params.provider.MethodSource;
10+
11+
/**
12+
* Unit tests for the Haversine formula implementation.
13+
* This class uses parameterized tests to verify the distance calculation
14+
* between various geographical coordinates.
15+
*/
16+
final class HaversineTest {
17+
18+
// A small tolerance for comparing double values, since floating-point
19+
// arithmetic is not always exact. A 1km tolerance is reasonable for these distances.
20+
private static final double DELTA = 1.0;
21+
22+
/**
23+
* Provides test cases for the haversine distance calculation.
24+
* Each argument contains: lat1, lon1, lat2, lon2, and the expected distance in kilometers.
25+
*
26+
* @return a stream of arguments for the parameterized test.
27+
*/
28+
static Stream<Arguments> haversineTestProvider() {
29+
return Stream.of(
30+
// Case 1: Distance between Paris, France and Tokyo, Japan
31+
Arguments.of(48.8566, 2.3522, 35.6895, 139.6917, 9712.0),
32+
33+
// Case 2: Distance between New York, USA and London, UK
34+
Arguments.of(40.7128, -74.0060, 51.5074, -0.1278, 5570.0),
35+
36+
// Case 3: Zero distance (same point)
37+
Arguments.of(52.5200, 13.4050, 52.5200, 13.4050, 0.0),
38+
39+
// Case 4: Antipodal points (opposite sides of the Earth)
40+
// Should be approximately half the Earth's circumference (PI * radius)
41+
Arguments.of(0.0, 0.0, 0.0, 180.0, 20015.0));
42+
}
43+
44+
/**
45+
* Tests the haversine method with various sets of coordinates.
46+
*
47+
* @param lat1 Latitude of the first point.
48+
* @param lon1 Longitude of the first point.
49+
* @param lat2 Latitude of the second point.
50+
* @param lon2 Longitude of the second point.
51+
* @param expectedDistance The expected distance in kilometers.
52+
*/
53+
@ParameterizedTest
54+
@MethodSource("haversineTestProvider")
55+
@DisplayName("Test Haversine distance calculation for various coordinates")
56+
void testHaversine(double lat1, double lon1, double lat2, double lon2, double expectedDistance) {
57+
double actualDistance = Haversine.haversine(lat1, lon1, lat2, lon2);
58+
assertEquals(expectedDistance, actualDistance, DELTA);
59+
}
60+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.thealgorithms.recursion;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertNotNull;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
6+
import static org.junit.jupiter.api.Assertions.assertTrue;
7+
8+
import java.math.BigInteger;
9+
import java.util.stream.Stream;
10+
import org.junit.jupiter.api.Test;
11+
import org.junit.jupiter.params.ParameterizedTest;
12+
import org.junit.jupiter.params.provider.MethodSource;
13+
import org.junit.jupiter.params.provider.ValueSource;
14+
15+
class SylvesterSequenceTest {
16+
17+
/**
18+
* Provides test cases for valid Sylvester sequence numbers.
19+
* Format: { n, expectedValue }
20+
*/
21+
static Stream<Object[]> validSylvesterNumbers() {
22+
return Stream.of(new Object[] {1, BigInteger.valueOf(2)}, new Object[] {2, BigInteger.valueOf(3)}, new Object[] {3, BigInteger.valueOf(7)}, new Object[] {4, BigInteger.valueOf(43)}, new Object[] {5, BigInteger.valueOf(1807)}, new Object[] {6, new BigInteger("3263443")},
23+
new Object[] {7, new BigInteger("10650056950807")}, new Object[] {8, new BigInteger("113423713055421844361000443")});
24+
}
25+
26+
@ParameterizedTest
27+
@MethodSource("validSylvesterNumbers")
28+
void testSylvesterValidNumbers(int n, BigInteger expected) {
29+
assertEquals(expected, SylvesterSequence.sylvester(n), "Sylvester sequence value mismatch for n=" + n);
30+
}
31+
32+
/**
33+
* Test edge case for n <= 0 which should throw IllegalArgumentException
34+
*/
35+
@ParameterizedTest
36+
@ValueSource(ints = {0, -1, -10, -100})
37+
void testSylvesterInvalidZero(int n) {
38+
assertThrows(IllegalArgumentException.class, () -> SylvesterSequence.sylvester(n));
39+
}
40+
41+
/**
42+
* Test a larger number to ensure no overflow occurs.
43+
*/
44+
@Test
45+
void testSylvesterLargeNumber() {
46+
int n = 10;
47+
BigInteger result = SylvesterSequence.sylvester(n);
48+
assertNotNull(result);
49+
assertTrue(result.compareTo(BigInteger.ZERO) > 0, "Result should be positive");
50+
}
51+
}

0 commit comments

Comments
 (0)