Skip to content

Commit e48e459

Browse files
authored
Merge pull request #26 from panos-kakos/master
Update from master
2 parents b23e156 + ffddf2b commit e48e459

182 files changed

Lines changed: 4280 additions & 1356 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/maximumsubarray/KadaneAlgorithm.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
public class KadaneAlgorithm {
77

8-
private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.class.getName());
8+
private Logger logger = LoggerFactory.getLogger(KadaneAlgorithm.class.getName());
99

1010
public int maxSubArraySum(int[] arr) {
1111

@@ -14,15 +14,15 @@ public int maxSubArraySum(int[] arr) {
1414
int end = 0;
1515

1616
int maxSoFar = arr[0], maxEndingHere = arr[0];
17-
for (int i = 1; i < size; i++) {
1817

19-
if (arr[i] > maxEndingHere + arr[i]) {
20-
start = i;
18+
for (int i = 1; i < size; i++) {
19+
maxEndingHere = maxEndingHere + arr[i];
20+
if (arr[i] > maxEndingHere) {
2121
maxEndingHere = arr[i];
22-
} else {
23-
maxEndingHere = maxEndingHere + arr[i];
22+
if (maxSoFar < maxEndingHere) {
23+
start = i;
24+
}
2425
}
25-
2626
if (maxSoFar < maxEndingHere) {
2727
maxSoFar = maxEndingHere;
2828
end = i;

algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/maximumsubarray/KadaneAlgorithmUnitTest.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
class KadaneAlgorithmUnitTest {
88

99
@Test
10-
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
10+
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturnsExpectedResult() {
1111
//given
1212
int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 };
1313
//when
@@ -27,7 +27,7 @@ void givenArrayWithAllNegativeNumbersWhenMaximumSubarrayThenReturnsExpectedResul
2727
//then
2828
assertEquals(-1, maxSum);
2929
}
30-
30+
3131
@Test
3232
void givenArrayWithAllPosiitveNumbersWhenMaximumSubarrayThenReturnsExpectedResult() {
3333
//given
@@ -39,4 +39,15 @@ void givenArrayWithAllPosiitveNumbersWhenMaximumSubarrayThenReturnsExpectedResul
3939
assertEquals(10, maxSum);
4040
}
4141

42+
@Test
43+
void givenArrayToTestStartIndexWhenMaximumSubarrayThenReturnsExpectedResult() {
44+
//given
45+
int[] arr = new int[] { 1, 2, -1, 3, -6, -2 };
46+
//when
47+
KadaneAlgorithm algorithm = new KadaneAlgorithm();
48+
int maxSum = algorithm.maxSubArraySum(arr);
49+
//then
50+
assertEquals(5, maxSum);
51+
}
52+
4253
}

algorithms-modules/algorithms-miscellaneous-7/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
- [Algorithm to Identify and Validate a Credit Card Number](https://www.baeldung.com/java-validate-cc-number)
44
- [Find the N Most Frequent Elements in a Java Array](https://www.baeldung.com/java-n-most-frequent-elements-array)
55
- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
6+
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
67
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.algorithms.latlondistance;
2+
3+
public class EquirectangularApproximation {
4+
5+
private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM
6+
7+
public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
8+
double lat1Rad = Math.toRadians(lat1);
9+
double lat2Rad = Math.toRadians(lat2);
10+
double lon1Rad = Math.toRadians(lon1);
11+
double lon2Rad = Math.toRadians(lon2);
12+
13+
double x = (lon2Rad - lon1Rad) * Math.cos((lat1Rad + lat2Rad) / 2);
14+
double y = (lat2Rad - lat1Rad);
15+
double distance = Math.sqrt(x * x + y * y) * EARTH_RADIUS;
16+
17+
return distance;
18+
}
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.baeldung.algorithms.latlondistance;
2+
3+
public class HaversineDistance {
4+
private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM
5+
6+
public static double calculateDistance(double startLat, double startLong,
7+
double endLat, double endLong) {
8+
9+
double dLat = Math.toRadians((endLat - startLat));
10+
double dLong = Math.toRadians((endLong - startLong));
11+
12+
startLat = Math.toRadians(startLat);
13+
endLat = Math.toRadians(endLat);
14+
15+
double a = haversine(dLat) + Math.cos(startLat) * Math.cos(endLat) * haversine(dLong);
16+
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
17+
18+
return EARTH_RADIUS * c;
19+
}
20+
21+
public static double haversine(double val) {
22+
return Math.pow(Math.sin(val / 2), 2);
23+
}
24+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.baeldung.algorithms.latlondistance;
2+
3+
public class VincentyDistance {
4+
5+
// Constants for WGS84 ellipsoid model of Earth
6+
private static final double SEMI_MAJOR_AXIS_MT = 6378137;
7+
private static final double SEMI_MINOR_AXIS_MT = 6356752.314245;
8+
private static final double FLATTENING = 1 / 298.257223563;
9+
private static final double ERROR_TOLERANCE = 1e-12;
10+
11+
public static double calculateDistance(double latitude1, double longitude1, double latitude2, double longitude2) {
12+
double U1 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude1)));
13+
double U2 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude2)));
14+
15+
double sinU1 = Math.sin(U1);
16+
double cosU1 = Math.cos(U1);
17+
double sinU2 = Math.sin(U2);
18+
double cosU2 = Math.cos(U2);
19+
20+
double longitudeDifference = Math.toRadians(longitude2 - longitude1);
21+
double previousLongitudeDifference;
22+
23+
double sinSigma, cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM;
24+
25+
do {
26+
sinSigma = Math.sqrt(Math.pow(cosU2 * Math.sin(longitudeDifference), 2) +
27+
Math.pow(cosU1 * sinU2 - sinU1 * cosU2 * Math.cos(longitudeDifference), 2));
28+
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * Math.cos(longitudeDifference);
29+
sigma = Math.atan2(sinSigma, cosSigma);
30+
sinAlpha = cosU1 * cosU2 * Math.sin(longitudeDifference) / sinSigma;
31+
cosSqAlpha = 1 - Math.pow(sinAlpha, 2);
32+
cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
33+
if (Double.isNaN(cos2SigmaM)) {
34+
cos2SigmaM = 0;
35+
}
36+
previousLongitudeDifference = longitudeDifference;
37+
double C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha));
38+
longitudeDifference = Math.toRadians(longitude2 - longitude1) + (1 - C) * FLATTENING * sinAlpha *
39+
(sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2))));
40+
} while (Math.abs(longitudeDifference - previousLongitudeDifference) > ERROR_TOLERANCE);
41+
42+
double uSq = cosSqAlpha * (Math.pow(SEMI_MAJOR_AXIS_MT, 2) - Math.pow(SEMI_MINOR_AXIS_MT, 2)) / Math.pow(SEMI_MINOR_AXIS_MT, 2);
43+
44+
double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
45+
double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
46+
47+
double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2)) -
48+
B / 6 * cos2SigmaM * (-3 + 4 * Math.pow(sinSigma, 2)) * (-3 + 4 * Math.pow(cos2SigmaM, 2))));
49+
50+
double distanceMt = SEMI_MINOR_AXIS_MT * A * (sigma - deltaSigma);
51+
return distanceMt / 1000;
52+
}
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.algorithms.latlondistance;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertTrue;
6+
7+
class GeoDistanceUnitTest {
8+
@Test
9+
public void testCalculateDistance() {
10+
double lat1 = 40.714268; // New York
11+
double lon1 = -74.005974;
12+
double lat2 = 34.0522; // Los Angeles
13+
double lon2 = -118.2437;
14+
15+
double equirectangularDistance = EquirectangularApproximation.calculateDistance(lat1, lon1, lat2, lon2);
16+
double haversineDistance = HaversineDistance.calculateDistance(lat1, lon1, lat2, lon2);
17+
double vincentyDistance = VincentyDistance.calculateDistance(lat1, lon1, lat2, lon2);
18+
19+
double expectedDistance = 3944;
20+
assertTrue(Math.abs(equirectangularDistance - expectedDistance) < 100);
21+
assertTrue(Math.abs(haversineDistance - expectedDistance) < 10);
22+
assertTrue(Math.abs(vincentyDistance - expectedDistance) < 0.5);
23+
24+
}
25+
26+
}

apache-httpclient-2/src/main/java/com/baeldung/tlsversion/ClientTlsVersionExamples.java

Lines changed: 36 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,43 @@
11
package com.baeldung.tlsversion;
22

3+
import java.io.IOException;
4+
35
import javax.net.ssl.SSLSocket;
46

5-
import org.apache.http.HttpEntity;
6-
import org.apache.http.client.methods.CloseableHttpResponse;
7-
import org.apache.http.client.methods.HttpGet;
8-
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
9-
import org.apache.http.impl.client.CloseableHttpClient;
10-
import org.apache.http.impl.client.HttpClients;
11-
import org.apache.http.ssl.SSLContexts;
12-
import org.apache.http.util.EntityUtils;
13-
14-
import java.io.IOException;
7+
import org.apache.hc.client5.http.classic.methods.HttpGet;
8+
import org.apache.hc.client5.http.config.TlsConfig;
9+
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
10+
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
11+
import org.apache.hc.client5.http.impl.classic.HttpClients;
12+
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
13+
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
14+
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
15+
import org.apache.hc.core5.http.HttpEntity;
16+
import org.apache.hc.core5.http.io.entity.EntityUtils;
17+
import org.apache.hc.core5.http.ssl.TLS;
18+
import org.apache.hc.core5.ssl.SSLContexts;
19+
import org.apache.hc.core5.util.Timeout;
1520

1621
public class ClientTlsVersionExamples {
17-
1822
public static CloseableHttpClient setViaSocketFactory() {
19-
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
20-
SSLContexts.createDefault(),
21-
new String[] { "TLSv1.2", "TLSv1.3" },
22-
null,
23-
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
23+
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
24+
.setDefaultTlsConfig(TlsConfig.custom()
25+
.setHandshakeTimeout(Timeout.ofSeconds(30))
26+
.setSupportedProtocols(TLS.V_1_2, TLS.V_1_3)
27+
.build())
28+
.build();
2429

25-
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
30+
return HttpClients.custom()
31+
.setConnectionManager(cm)
32+
.build();
2633
}
2734

2835
public static CloseableHttpClient setTlsVersionPerConnection() {
2936
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
30-
3137
@Override
3238
protected void prepareSocket(SSLSocket socket) {
33-
String hostname = socket.getInetAddress().getHostName();
39+
String hostname = socket.getInetAddress()
40+
.getHostName();
3441
if (hostname.endsWith("internal.system.com")) {
3542
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
3643
} else {
@@ -39,23 +46,26 @@ protected void prepareSocket(SSLSocket socket) {
3946
}
4047
};
4148

42-
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
49+
HttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
50+
.setSSLSocketFactory(sslsf)
51+
.build();
52+
53+
return HttpClients.custom()
54+
.setConnectionManager(connManager)
55+
.build();
56+
4357
}
4458

4559
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
4660
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar
4761
public static CloseableHttpClient setViaSystemProperties() {
4862
return HttpClients.createSystem();
4963
// Alternatively:
50-
// return HttpClients.custom().useSystemProperties().build();
64+
//return HttpClients.custom().useSystemProperties().build();
5165
}
5266

5367
public static void main(String[] args) throws IOException {
54-
// Alternatively:
55-
// CloseableHttpClient httpClient = setTlsVersionPerConnection();
56-
// CloseableHttpClient httpClient = setViaSystemProperties();
57-
try (CloseableHttpClient httpClient = setViaSocketFactory();
58-
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
68+
try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
5969

6070
HttpEntity entity = response.getEntity();
6171
EntityUtils.consume(entity);

0 commit comments

Comments
 (0)