Merging into own fork (#3)
* [BAEL-7621] - Fixed integration test of spring-hibernate-5 module by introducing H2 database * BAEL-1985: Added Examples showing how to Initialize HashSet when it's constructed (#4715) * Added Class for Initalizing HahsSet * Updated Class name * Delete InitializingSetTest.java * Copy list to another list examples (#4725) * Update README.MD (#4720) * [BAEL-7621] - Fixed integration test of spring-hibernate-5 module by introducing H2 database (#4728) * [BAEL-7645] - Fixed integration test of spring-jpa module through H2 inmemory DB * BAEL-1814 Guide to Spring Webflux (#4450) * BAEL-1814 Guide to Spring Webflux -Added files for Employee reactive application -Updated pom.xml for Spring Security * BAEL-1814 Guide to Spring Webflux -Added EmployeeControllerTest -Updated method name in EmployeeController and corrected secured url in EmployeeWebSecurityConfig * BAEL-1814 Guide to spring webflux -Fixed security config, now only specific url prompts for authentication and not all endpoints -Removed @WithMockUser as it is not needed now * BAEL-1814 Guide To Webflux -Feedback incorporation * BAEL-1814 Spring Webflux Guide -Formatted coded for EmployeeWebSocketHandler. * Update and rename EmployeeControllerTest.java to EmployeeControllerUnitTest.java * BAEL-1814 Guide to spring webflux -Fixed EmployeeControllerUnitTest.java * BAEL - 1916 (#4729) Code refactored * Renamed test methods to use BDD style * Fixed integration test of spring-jpa module through inmemory H2 DB (#4740) * [BAEL-7621] - Fixed integration test of spring-hibernate-5 module by introducing H2 database * [BAEL-7645] - Fixed integration test of spring-jpa module through H2 inmemory DB * guide to jmapper * [BAEL-7651] - Fixed integration tests of spring-security-mvc-custom module by adding proper authentication manager * clean only generated files * added spring-rest-hal-browser code (#4701) * Added spring-rest-template * Updated README.md file * Updated README.md file * Update Makefile * Update Makefile * moved AuthenticationFailureHandler example to spring-security-mvc-login * trying out separate modules in the integration profile * maven cleanup * fixing name of module * running group 2 * running group 1 * fixing relative path * Update Makefile * Update Makefile * Update JMapperIntegrationTest.java * Update JMapperRelationalIntegrationTest.java * Update MultipartFileUploadClient.java * BAEL-1914 refactor (#4749) * Server Sent Events example using Spring Webflux and React * spring security custom AuthenticationFailureHandler * refactor * moved SSE to branch * remove pom properties * moved AuthenticationFailureHandler example to spring-security-mvc-login * added link * trying out profile-driven build * minor maven cleanup * activating group 2 * Update README.md * BAEL-1850 (#4744) * Micronaut server * More server stuff; create client and test * Rename directory, new concerete client example * Remove hello-world directory from micronaut * Update MavenWrapperDownloader.java * running group 1, and small logging fix * jnosql * live test properly categorized * temporarily making a test live * moving the libraries module from group 1 * group 2 * enabling group 3 * * Added changes for BAEL-1922 Enable CORS in Spring Webflux (#4724) * BAEL-2018 (#4753) * BAEL-2018 * Update Animal.java * rename * running group 3 * jmeter excluded * running group 2 * properly classifying a testclear * live tests * BAEL-1838 (#4692) * #BAEL-1838 code samples. Renamed LambdaKotlinTest to have the build succeed. * #BAEL-1838 code samples w/inheritance. * #BAEL-1838 renamed logger helper function to getLogger to avoid confusion. * #BAEL-1838 renamed logger helper function to getLogger to avoid confusion. * BEAL-1985 - Removed Java 9 Example (#4734) * Added Class for Initalizing HahsSet * Updated Class name * Delete InitializingSetTest.java * Modified HashSet Initilization Example * Removed Java 9 Example * Update HashSetInitalizingUnitTest.java * Update HashSetInitalizingUnitTest.java * Update HashSetInitalizingUnitTest.java * Update HashSetInitalizingUnitTest.java * group 3.2 * enabling 3.1 * running group 3 * Update README.md Documenting the new default profile. * fixing the default profile testing config * groups 2 and 3 * minor major cleanup * BAEL-1907 Created new module spring-testing * new integration-lite profile * integration-lite work * BAEL-1862 Move the Junit 5 logic in the right module (#4747) * BAEL-1862 Move the Junit 5 logic in the right module -Moved Method Orders Tests from tutorails/junit5 project into correct project tutorials/testing-modules/junit-5 -Removed tutorials/junit5 project * Update DefaultOrderOfExecutionTest.java * Update README.md * BAEL-1862 Move the Junit 5 logic in the right module -Renamed *Test to *UnitTest * Update README.md * maven cleanup work * logging cleanup * BAEL-1907 Corrected formatting * working through modules * maven cleanup * trying problematic modules * integration heavy profile * maven work * Bael 1864 (#4727) * running project without building tests * include the DataCheck class * Update TestFail.java * guide to jmapper (#4745) * guide to jmapper * Update JMapperIntegrationTest.java * Update JMapperRelationalIntegrationTest.java * dupirefr/dupire.francois+pro@gmail.com [BAEL-1981] Query entities by dates and times with Spring Data JPA (#4737) * [BAEL-1981] Article entity and repository + tests * [BAEL-1981] Removing unnecessary fields * moving long-running module * BAEL-1992 * maven cleanup work * BAEL-1818 - A Guide to Connection Pools in Java (#4735) * Strange git issue with README.MD, wouldn't revert the file * Initial Commit * Initial Commit * Update pom.xml * Update pom.xml * Initial Commit * Update pom.xml * Update source files * Update source files * Update source files * Update source files * Update Application.java * Update pom.xml * Update HikariCPDataSourceUnitTest class * Update HikariCPDataSourceUnitTest.java * Update pom.xml * Update unit test classes * Update BasicConnectionPoolUnitTest.java * Fix indentation in DBCDDataSource class * Update DBCPDataSource.java * Update BasicConnectionPool class * Update BasicConnectionPool class * Update BasicConnectionPool.java * Update BasicConnectionPool.java * Update pom.xml * Update pom.xml * BAEL-1818 Refactored getConnection(), added shutdown(), cleaned up pom.xml * BAEL-1818 Removed getConnectionPool(), upgraded c3po version * BAEL-1818 Deleted obsolete connectionpool module * BAEL-1818 Deleted obsolete connectionpool module * move jmapper to libraries-data * [BAEL-7635] Removed test generated files : Will be gitignored * [BAEL-7635] - Commented out sortpom-maven-plugin that changes pom.xml in every build, added new entries in .gitignore * BAEL-1852 - Testing an Abstract Class with JUnit (#4773) * BAEL-1852 - Testing an Abstract Class with JUnit * Fixed test method names and class names according to naming compliances. * BAEL-1934 (#4768) * Bean Object, server side and client side example for event streaming example * BAEL-1628 Access a File from the Classpath in a Spring Application * inputstream retrieval added * Removed files related to evaluation article * + Aligning code to the article. Removed Utility methods and classes * BAEL - 1628 * PMD fixes * Code Review changes Refactored : whenResourceUtils_thenReadSuccessful * BAEL-1934 * +indentation correction in pom.xml * synced with master * indentation correction * update to spring 5 * Bael 2018 (#4774) * BAEL-2018 * Update Animal.java * rename * tests added * generic type shorten * update test * BAEL-1911 - Fixing author's review comments (#4782) * Strange git issue with README.MD, wouldn't revert the file * Fixing review comments * BAEL-1911 Refactored SQL code, fixed formatting * fix swagger parent * Update pom.xml * Update pom.xml * Overriding System time for testing (#4779) * Overriding System time for testing * Remove Joda Date Time examples * BAEL-1728: add java instrumentation * dupirefr/dupire.francois+pro@gmail.com [BAEL-1981] Spring data jpa dates (#4795) * [BAEL-1981] Article entity and repository + tests * [BAEL-1981] Removing unnecessary fields * [BAEL-1981] spring-data-jpa module creation * BAEL-1818 lamdba instead of loop; isEmpty() instead of == 0 (#4791) * BAEL-2018 Moved to core-java-collections (#4796) * BAEL-1691: comparing embedded servlet containers in spring boot * vaadin spring * format * remove reactive ex * move to reactive, extract mongodb ex * PR for http://jira.baeldung.com/browse/BAEL-1947 Spring Boot Vue (#4687) * commit first as binodpanta * revert test change * A short example of real-time event streaming using Spring WebFlux * Code for http://jira.baeldung.com/browse/BAEL-1527 * remove unrelated files * Apply feedback changes to rename test and remove link from readme file, ongoing work * Update formatting fixes to code and add pom changes, that partially fix test runnning issues in IDE but not in cmdline * Apply Eclipse formatter to test code and apply suggested pom fixes * BAEL-1527 Formatting fix in pom.xml * Use string.format to cleanup logging code * BAEL-1527 Changed logging pattern * Start the spring-boot-vue module, WIP * some small updates with comments * Add index html template page * merge pom.xml fixes * Add integration test with MockMvc to verify index.html content is rendered correctly * fix up pom merge issues * merge issues fix for pom * pom end of file newline * Update README.md * Update README.md (#4706) * add links (#4804) * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.MD * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * move mongodb ex * fix readme files * Bael 1832 (#4748) * @Primary annotation * @Primary annotation Employee name * Update PrimaryApplication.java * @Primary annotation with @Component * add security exc * added readme * added link * BAEL-2030 remove first element from list (#4803) * BAEL-2042 JavaFaker unit tests * Moved javafaker unit tests to testing-modules * Update PushController.java * * added examples of filtering collections using Streams, Apache CollectionUtils, Guava and Eclipse Collections * * Added examples for java-9 filtering collector * * minor fixes and cleaning duties * add elements to list (#4814) * BAEL-1960: Custom appender for log4j (#4731) * BAEL-1960: Custom appender for log4j * Changes as per suggestion to BAEL-1960 * Changes as [er review for BAEL-1960 * Changes for formatting as per suggestion. * BAEL-1960. Copied pom.xml from master and pasted my changes against it. * Chnages for spaces instead of tabs. * Changes for spaces instead of tabs. * PrincipalExtractor and AuthoritiesExtractor example * Bael 1743 improved (#4826) * compile only for firefox * added parent module * changed artifact id * commenting out problematic modules in the integration-lite build * integratio-lite profile work * integration-lite work * update spring data elasticsearch * BAEL-1818 A Simple Guide to Connection Pooling in Java (#4823) * Initial Commit * Update parent pom.xml * Update BasicConnectionPool class * Update BasicConnectionPool class * BAEL-1818 removed code from core-java module, cleaned up a little pom files * BAEL-1818 moved the code from connectionpool.connectionpools package to connectionpool * added link * integration-lite trying out a few modules * moved PrincipalExtractor and AuthoritiesExtractor example to spring-5-security module * removed comment on pom * [refs#BAEL-1992] Minor refactoring * BAEL-1983 Intialize a HashMap in Java (#4819) * move mqtt project * added link * Add items to list in core-java-collections (#4841) * [BAEL-7608] - Fixed spring-5-reactive integration tests * [BAEL-7608] - Reverted NettyContext to Embedded Tomcat example with Async = true * [BAEL-7608] - Removed unused imports * Update pom.xml * [BAEL-7609] - Fixed spring-boot integration tests * Added PR files for BAEL-2031 (#4844) * Added source files for BAEL-2031 * Added test files for BAEL-2031 * upgrade sockets to spring5 * BAEL-1979 Added examples for SnakeYAML Library (#4802) * BAEL-1979 Added examples for SnakeYAML Library * BAEL-1979 Moved the snakeyaml related code to libraries module * BAEL-1979 Removed the System.out.println() statements and converted the assertTrue to assertEquals wherever possible. * BAEL-1979 Removed println statements, small formatting fix in pom.xml * [BAEL-7608] - Fixed SecurityIntegrationTest with redirecting to login * Bael 1555 - Improve Example (#4852) * BAEL-1555 * Corrected indents and spacing * RequestMapping to GetMapping * Improved Performance For Concurrent Users * BAEL-1958 Log using SLF4J (#4790) * Log using SLF4J Jira Ticket: BAEL-1958 * Incorporate first review comments * Bael 2023 (#4851) * bael-2023: removing all occurrences of a value from a list * adjusting examples to match the article * [BAEL-7437] - Added spring tx dependency to fix spring-mvc-simple junit 5 TCs * add libraries server project * remove extra files * BAEL-1865 - Java Objects Sizes (#4584) * BAEL-1865 - Java Objects Sizes * BAEL-1865 - PR fix * OAuth2 Principal and Authorities example - refactor and added example using custom authorization server * Server-Sent Evensts * BAEL-1936 Use of FilenameFilter (#4520) * Added tests for FilenameFilter demo -added a test to show FilenameFilter implementation -added another test to show similar functionality using Predicate * refactored code to get directory at a single location * fixing formatting * changed test class name to conform to custom rule UnitTestNamingConventionRule lists the allowed test class names. Added ManualTest at the end to conform to the rule. * add new module * Update pom.xml (#4843) * BAEL-1861 - Running JUnit tests from a Java application (#4526) * BAEL-1562 - Thymeleaf sample working * BAEL-1562 Code added for Fragments sample * BAEL-1562 - Last correction for the test * BAEL-1562 - Thymeleaf sample working * BAEL-1562 Code added for Fragments sample * BAEL-1562 - Last correction for the test * Updates Thymeleaf version to 3.0.9.RELEASE * Added msf4j projects * updated msf4j project folder * fixed issue with spring-thymeleaf/pom.xml * Removed depedency-reduced-pom.xml * Whitespacing fix * Strange git issue with README.MD, wouldn't revert the file * Added jupiter api * Corrected junit test * Added test engine to plugin * Removed extra tag * Little fixes to junit4 and junit4 run from java * Removed scope from pom.xml * Removed bin file from testing * Slight changes for PMD * Slight changes for PMD * ok, moved code to another folder * Renamed and fixed runjunitfromjava * moved test classes to test folder * moved main to src/java * BAEL-1861 Moved test running classes to src/test/java * Added changes to runjunitfromjava * Added changes to runjunitfromjava * BAEL-1861 Changed test execution code examples * BAEL-1861 Changed test execution code examples; formatting * Bael 1852 - Test case code is aligned to support Junit5 (#4847) * add prototype bean ex with function * remove extra classes * remove extra import * separate configs * separate configs * Update AppConfig.java * Code update to support Junit5 * BAEL-1979 Added examples for SnakeYAML Library (#4802) * BAEL-1979 Added examples for SnakeYAML Library * BAEL-1979 Moved the snakeyaml related code to libraries module * BAEL-1979 Removed the System.out.println() statements and converted the assertTrue to assertEquals wherever possible. * BAEL-1979 Removed println statements, small formatting fix in pom.xml * BAEL-1852 Renamed one test method, fixed formatting * Bael 1273 Spring RSS Feed View (#4707) * Added example for BAEL-1273 - rss feed with Spring. * Fixed javadoc * Removed useless SpringBootServletInitializer in RSS app's launcher * Explicitely added Spring Boot starting class in pom.xml to prevent errors in package phase. * Adding files for Exception Handling article (#4507) * Adding files for Exception Handling article * Updating files * Test folder * testing renaming * Formatting and Naming Conventions This commit reworks the code for the Intro to Exception Handling article, ensuring that packages and classes are formatted and named according to site standards. * Update SseEmitterController.java (#4864) * fixing package hierarchy (*.list.list.listoflist -> *.list.listoflist) (#4879) * moved examples for 'removing all occurrences of an element from a list' to core-java-collections (#4878) * BAEL-1958 Moved the example to logging-modules (#4886) * Example for removing first element of array (BAEL-2029) (#4836) * Example for removing first element of array (BAEL-2029) * Use AssertJ assertions * BAEL-1986 List initialization in one line (#4696) * list initializations in one line * Enhance after review * formatting and naming * Formatting and renaming 2 * Unit tests and DequeBasedSynchronizedStack added up * Unit tests method names and class names modified as per the guidelines * BAEL-1840 Builder Pattern in Kotlin (#4730) * builder pattern in kotlin * builder pattern in kotlin new-line * deleted Sandbox, added unit test * add other tests * named and default parameters builder * Make FoodOrderNamed a data class * BAEL-1861 Replaced real tests with demo test "placeholders" (#4887) * Spring Boot and Angular E-Commerce Application (#4874) * Spring Boot and Angular E-Commerce Application * Spring Boot and Angular E-Commerce Application pom.xml updated * Spring Boot and Angular E-Commerce Application tests added * BAEL-7965 JMH module fails when build (#4888) * BAEL-7965 JMH module fails when build -Added jmh module in default profile in parent pom * Update pom.xml moved jmh module to integration profile * Create pom.xml * Create FunctionTestSuite.java BAEL-1857 * BAEL-1857 Running Parallel JUnit Tests with Maven * BAEL-1901 and BAEL-1555 add links (#4892) * BAEL-1766: Update README * BAEL-1853: add link to article * BAEL-1801: add link to article * Added links back to articles * Add links back to articles * BAEL-1795: Update README * BAEL-1901 and BAEL-1555 add links back to article * [BAEL-1967] - Custom validation MessageSource in Spring Boot * POM file updated for BAEL-1967 * BAEL-1704: Non-Trivial Work in Kotlin vs Java (#4861) * BAEL-1704: Non-Trivial Work in Kotlin vs Java * BAEL-1704: Non-Trivial Work in Kotlin vs Java Renaming one test class * Bael 1964 (#4881) * Added initial code for BAEL-1964, in-memory authentication application * Switched to default security encoder instead of a specific one * Fix typo (#4897) * add new module * fix typo * [BAEL-7670] Added logback.xml in missing modules in src/main/resources
This commit is contained in:
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerPrimeChecker implements PrimeChecker<Long>{
|
||||
|
||||
@Override
|
||||
public boolean isPrime(Long number) {
|
||||
BigInteger bigInt = BigInteger.valueOf(number);
|
||||
return bigInt.isProbablePrime(100);
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class BruteForcePrimeChecker implements PrimeChecker<Integer> {
|
||||
|
||||
@Override
|
||||
public boolean isPrime(Integer number) {
|
||||
|
||||
return number > 2 ? IntStream.range(2, number)
|
||||
.noneMatch(n -> (number % n == 0)) : false;
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class OptimisedPrimeChecker implements PrimeChecker<Integer> {
|
||||
|
||||
@Override
|
||||
public boolean isPrime(Integer number) {
|
||||
return number > 2 ? IntStream.rangeClosed(2, (int) Math.sqrt(number))
|
||||
.noneMatch(n -> (number % n == 0)) : false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
public interface PrimeChecker <T> {
|
||||
|
||||
public boolean isPrime( T number );
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import org.apache.commons.math3.primes.Primes;
|
||||
|
||||
public class PrimesPrimeChecker implements PrimeChecker<Integer>{
|
||||
|
||||
@Override
|
||||
public boolean isPrime(Integer number) {
|
||||
return Primes.isPrime(number);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class FloatingPointArithmetic {
|
||||
public static void main(String[] args) {
|
||||
|
||||
double a = 13.22;
|
||||
double b = 4.88;
|
||||
double c = 21.45;
|
||||
|
||||
System.out.println("a = " + a);
|
||||
System.out.println("b = " + b);
|
||||
System.out.println("c = " + c);
|
||||
|
||||
double sum_ab = a + b;
|
||||
System.out.println("a + b = " + sum_ab);
|
||||
|
||||
double abc = a + b + c;
|
||||
System.out.println("a + b + c = " + abc);
|
||||
|
||||
double ab_c = sum_ab + c;
|
||||
System.out.println("ab + c = " + ab_c);
|
||||
|
||||
double sum_ac = a + c;
|
||||
System.out.println("a + c = " + sum_ac);
|
||||
|
||||
double acb = a + c + b;
|
||||
System.out.println("a + c + b = " + acb);
|
||||
|
||||
double ac_b = sum_ac + b;
|
||||
System.out.println("ac + b = " + ac_b);
|
||||
|
||||
double ab = 18.1;
|
||||
double ac = 34.67;
|
||||
double sum_ab_c = ab + c;
|
||||
double sum_ac_b = ac + b;
|
||||
System.out.println("ab + c = " + sum_ab_c);
|
||||
System.out.println("ac + b = " + sum_ac_b);
|
||||
|
||||
BigDecimal d = new BigDecimal(String.valueOf(a));
|
||||
BigDecimal e = new BigDecimal(String.valueOf(b));
|
||||
BigDecimal f = new BigDecimal(String.valueOf(c));
|
||||
|
||||
BigDecimal def = d.add(e).add(f);
|
||||
BigDecimal dfe = d.add(f).add(e);
|
||||
|
||||
System.out.println("d + e + f = " + def);
|
||||
System.out.println("d + f + e = " + dfe);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
|
||||
import org.apache.commons.math3.util.Precision;
|
||||
import org.decimal4j.util.DoubleRounder;
|
||||
|
||||
public class Round {
|
||||
private static final double PI = 3.1415d;
|
||||
|
||||
public static void main (String args[]) {
|
||||
System.out.println("PI: " + PI);
|
||||
System.out.printf("Value with 3 digits after decimal point %.3f %n", PI);
|
||||
// OUTPUTS: Value with 3 digits after decimal point 3.142
|
||||
DecimalFormat df = new DecimalFormat("###.###");
|
||||
System.out.println(df.format(PI));
|
||||
System.out.println(round(PI, 3));
|
||||
System.out.println(roundNotPrecise(PI, 3));
|
||||
System.out.println(roundAvoid(PI, 3));
|
||||
System.out.println(Precision.round(PI, 3));
|
||||
System.out.println(DoubleRounder.round(PI, 3));
|
||||
}
|
||||
|
||||
public static double round(double value, int places) {
|
||||
if (places < 0) throw new IllegalArgumentException();
|
||||
|
||||
BigDecimal bd = new BigDecimal(Double.toString(value));
|
||||
bd = bd.setScale(places, RoundingMode.HALF_UP);
|
||||
return bd.doubleValue();
|
||||
}
|
||||
|
||||
public static double roundNotPrecise(double value, int places) {
|
||||
if (places < 0) throw new IllegalArgumentException();
|
||||
|
||||
BigDecimal bd = new BigDecimal(value);
|
||||
bd = bd.setScale(places, RoundingMode.HALF_UP);
|
||||
return bd.doubleValue();
|
||||
}
|
||||
|
||||
public static double roundAvoid(double value, int places) {
|
||||
double scale = Math.pow(10, places);
|
||||
double rounded = Math.round(value * scale) / scale;
|
||||
return rounded;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.nan;
|
||||
|
||||
/**
|
||||
* Sample usage of NaN.
|
||||
*
|
||||
*/
|
||||
public class NaNExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
NaNExample naNExample = new NaNExample();
|
||||
naNExample.demo();
|
||||
}
|
||||
|
||||
void demo() {
|
||||
undefined_operations_produce_NaN();
|
||||
operations_with_no_real_results_produce_NaN();
|
||||
operations_with_NaN_produce_NaN();
|
||||
comparison_with_NaN();
|
||||
check_if_a_value_is_NaN();
|
||||
assign_NaN_to_missing_values();
|
||||
}
|
||||
|
||||
void undefined_operations_produce_NaN() {
|
||||
System.out.println("Undefined Operations Produce NaN");
|
||||
final double ZERO = 0;
|
||||
System.out.println("ZERO / ZERO = " + (ZERO / ZERO));
|
||||
System.out.println("INFINITY - INFINITY = " + (Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY));
|
||||
System.out.println("INFINITY * ZERO = " + (Double.POSITIVE_INFINITY * ZERO));
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
void operations_with_no_real_results_produce_NaN() {
|
||||
System.out.println("Operations with no real results produce NaN");
|
||||
System.out.println("SQUARE ROOT OF -1 = " + Math.sqrt(-1));
|
||||
System.out.println("LOG OF -1 = " + Math.log(-1));
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
void operations_with_NaN_produce_NaN() {
|
||||
System.out.println("Operations with NaN produce NaN");
|
||||
System.out.println("2 + NaN = " + (2 + Double.NaN));
|
||||
System.out.println("2 - NaN = " + (2 - Double.NaN));
|
||||
System.out.println("2 * NaN = " + (2 * Double.NaN));
|
||||
System.out.println("2 / NaN = " + (2 / Double.NaN));
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
void assign_NaN_to_missing_values() {
|
||||
System.out.println("Assign NaN to Missing values");
|
||||
double salaryRequired = Double.NaN;
|
||||
System.out.println(salaryRequired);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
void comparison_with_NaN() {
|
||||
System.out.println("Comparison with NaN");
|
||||
final double NAN = Double.NaN;
|
||||
System.out.println("NaN == 1 = " + (NAN == 1));
|
||||
System.out.println("NaN > 1 = " + (NAN > 1));
|
||||
System.out.println("NaN < 1 = " + (NAN < 1));
|
||||
System.out.println("NaN != 1 = " + (NAN != 1));
|
||||
System.out.println("NaN == NaN = " + (NAN == NAN));
|
||||
System.out.println("NaN > NaN = " + (NAN > NAN));
|
||||
System.out.println("NaN < NaN = " + (NAN < NAN));
|
||||
System.out.println("NaN != NaN = " + (NAN != NAN));
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
void check_if_a_value_is_NaN() {
|
||||
System.out.println("Check if a value is NaN");
|
||||
double x = 1;
|
||||
System.out.println(x + " is NaN = " + (x != x));
|
||||
System.out.println(x + " is NaN = " + (Double.isNaN(x)));
|
||||
|
||||
x = Double.NaN;
|
||||
System.out.println(x + " is NaN = " + (x != x));
|
||||
System.out.println(x + " is NaN = " + (Double.isNaN(x)));
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
|
||||
public class Benchmarking {
|
||||
public static void main(String[] args) throws RunnerException, IOException {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public int number = Integer.MAX_VALUE;
|
||||
public int length = 0;
|
||||
public NumberOfDigits numberOfDigits= new NumberOfDigits();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void stringBasedSolution(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.stringBasedSolution(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void logarithmicApproach(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.logarithmicApproach(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void repeatedMultiplication(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void shiftOperators(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.shiftOperators(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void dividingWithPowersOf2(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void divideAndConquer(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.divideAndConquer(plan.number);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
public class NumberOfDigits {
|
||||
public int stringBasedSolution(int number) {
|
||||
int length = String.valueOf(number).length();
|
||||
return length;
|
||||
}
|
||||
|
||||
public int logarithmicApproach(int number) {
|
||||
int length = (int) Math.log10(number) + 1;
|
||||
return length;
|
||||
}
|
||||
|
||||
public int repeatedMultiplication(int number) {
|
||||
int length = 0;
|
||||
long temp = 1;
|
||||
while(temp <= number) {
|
||||
length++;
|
||||
temp *= 10;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int shiftOperators(int number) {
|
||||
int length = 0;
|
||||
long temp = 1;
|
||||
while(temp <= number) {
|
||||
length++;
|
||||
temp = (temp << 3) + (temp << 1);
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int dividingWithPowersOf2(int number) {
|
||||
int length = 1;
|
||||
if (number >= 100000000) {
|
||||
length += 8;
|
||||
number /= 100000000;
|
||||
}
|
||||
if (number >= 10000) {
|
||||
length += 4;
|
||||
number /= 10000;
|
||||
}
|
||||
if (number >= 100) {
|
||||
length += 2;
|
||||
number /= 100;
|
||||
}
|
||||
if (number >= 10) {
|
||||
length += 1;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int divideAndConquer(int number) {
|
||||
if (number < 100000){
|
||||
// 5 digits or less
|
||||
if (number < 100){
|
||||
// 1 or 2
|
||||
if (number < 10)
|
||||
return 1;
|
||||
else
|
||||
return 2;
|
||||
}else{
|
||||
// 3 to 5 digits
|
||||
if (number < 1000)
|
||||
return 3;
|
||||
else{
|
||||
// 4 or 5 digits
|
||||
if (number < 10000)
|
||||
return 4;
|
||||
else
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 6 digits or more
|
||||
if (number < 10000000) {
|
||||
// 6 or 7 digits
|
||||
if (number < 1000000)
|
||||
return 6;
|
||||
else
|
||||
return 7;
|
||||
} else {
|
||||
// 8 to 10 digits
|
||||
if (number < 100000000)
|
||||
return 8;
|
||||
else {
|
||||
// 9 or 10 digits
|
||||
if (number < 1000000000)
|
||||
return 9;
|
||||
else
|
||||
return 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class NumberOfDigitsDriver {
|
||||
private static NumberOfDigits numberOfDigits;
|
||||
|
||||
private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
|
||||
|
||||
static {
|
||||
numberOfDigits = new NumberOfDigits();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Testing all methods...");
|
||||
|
||||
long length = numberOfDigits.stringBasedSolution(602);
|
||||
LOG.info("String Based Solution : " + length);
|
||||
|
||||
length = numberOfDigits.logarithmicApproach(602);
|
||||
LOG.info("Logarithmic Approach : " + length);
|
||||
|
||||
length = numberOfDigits.repeatedMultiplication(602);
|
||||
LOG.info("Repeated Multiplication : " + length);
|
||||
|
||||
length = numberOfDigits.shiftOperators(602);
|
||||
LOG.info("Shift Operators : " + length);
|
||||
|
||||
length = numberOfDigits.dividingWithPowersOf2(602);
|
||||
LOG.info("Dividing with Powers of 2 : " + length);
|
||||
|
||||
length = numberOfDigits.divideAndConquer(602);
|
||||
LOG.info("Divide And Conquer : " + length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.pairsaddupnumber;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* Find all different pairs of numbers in an array that add up to a given sum - Complexity O(n)
|
||||
*/
|
||||
public class DifferentPairs {
|
||||
|
||||
/**
|
||||
* Show all different pairs using traditional "for" loop
|
||||
*
|
||||
* @param input - number's array
|
||||
* @param sum - given sum
|
||||
* @return - number's array with all existing pairs. This list will contain just one pair's element because
|
||||
* the other one can be calculated with SUM - element_1 = element_2
|
||||
*/
|
||||
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
|
||||
final List<Integer> allDifferentPairs = new ArrayList<>();
|
||||
// Aux. hash map
|
||||
final Map<Integer, Integer> pairs = new HashMap<>();
|
||||
for (int i : input) {
|
||||
if (pairs.containsKey(i)) {
|
||||
if (pairs.get(i) != null) {
|
||||
// Add pair to returned list
|
||||
allDifferentPairs.add(i);
|
||||
}
|
||||
// Mark pair as added to prevent duplicates
|
||||
pairs.put(sum - i, null);
|
||||
} else if (!pairs.containsValue(i)) {
|
||||
// Add pair to aux. hash map
|
||||
pairs.put(sum - i, i);
|
||||
}
|
||||
}
|
||||
return allDifferentPairs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show all different pairs using Java 8 stream API
|
||||
*
|
||||
* @param input - number's array
|
||||
* @param sum - given sum
|
||||
* @return - number's array with all existing pairs. This list will contain just one pair's element because
|
||||
* the other one can be calculated with SUM - element_1 = element_2
|
||||
*/
|
||||
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
|
||||
final List<Integer> allDifferentPairs = new ArrayList<>();
|
||||
// Aux. hash map
|
||||
final Map<Integer, Integer> pairs = new HashMap<>();
|
||||
IntStream.range(0, input.length).forEach(i -> {
|
||||
if (pairs.containsKey(input[i])) {
|
||||
if (pairs.get(input[i]) != null) {
|
||||
// Add pair to returned list
|
||||
allDifferentPairs.add(input[i]);
|
||||
}
|
||||
// Mark pair as added to prevent duplicates
|
||||
pairs.put(sum - input[i], null);
|
||||
} else if (!pairs.containsValue(input[i])) {
|
||||
// Add pair to aux. hash map
|
||||
pairs.put(sum - input[i], input[i]);
|
||||
}
|
||||
}
|
||||
);
|
||||
return allDifferentPairs;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.pairsaddupnumber;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* Find all existing pairs of numbers in an array that add up to a given sum - Complexity O(n^2) "Brute force"
|
||||
*/
|
||||
public class ExistingPairs {
|
||||
|
||||
/**
|
||||
* Show all existing pairs using traditional "for" loop
|
||||
*
|
||||
* @param input - number's array
|
||||
* @param sum - given sum
|
||||
* @return - number's array with all existing pairs. This list will contain just one pair's element because
|
||||
* the other one can be calculated with SUM - element_1 = element_2
|
||||
*/
|
||||
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
|
||||
final List<Integer> allExistingPairs = new ArrayList<>();
|
||||
for (int i = 0; i < input.length; i++) {
|
||||
for (int j = 0; j < input.length; j++) {
|
||||
if (j != i && (input[i] + input[j]) == sum) {
|
||||
allExistingPairs.add(input[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return allExistingPairs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show all existing pairs using Java 8 stream API
|
||||
*
|
||||
* @param input - number's array
|
||||
* @param sum - given sum
|
||||
* @return - number's array with all existing pairs. This list will contain just one pair's element because
|
||||
* the other one can be calculated with SUM - element_1 = element_2
|
||||
*/
|
||||
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
|
||||
final List<Integer> allExistingPairs = new ArrayList<>();
|
||||
IntStream.range(0, input.length).forEach(i ->
|
||||
IntStream.range(0, input.length)
|
||||
.filter(j -> i != j && input[i] + input[j] == sum)
|
||||
.forEach(j -> allExistingPairs.add(input[i]))
|
||||
);
|
||||
return allExistingPairs;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.pairsaddupnumber;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
|
||||
public class FindPairs {
|
||||
|
||||
public void execute(int[] input, int sum) {
|
||||
final StringBuilder inputArray = new StringBuilder();
|
||||
inputArray.append("{");
|
||||
IntStream.range(0, input.length).forEach(i -> inputArray.append(input[i] + ", "));
|
||||
inputArray.append("}");
|
||||
System.out.println(" Given number array: " + inputArray.toString());
|
||||
System.out.println(" Given sum: " + sum);
|
||||
/* Call services */
|
||||
getDifferentPairs(input, sum);
|
||||
getExistingPairs(input, sum);
|
||||
}
|
||||
|
||||
/**
|
||||
* Print all existing pairs for the given inputs: input array & sum number
|
||||
*/
|
||||
private static void getExistingPairs(int[] input, int sum) {
|
||||
List<Integer> pairs = new ArrayList<>();
|
||||
System.out.println("~ All existing pairs ~");
|
||||
|
||||
/* Traditional FOR loop */
|
||||
// Call method
|
||||
pairs = ExistingPairs.findPairsWithForLoop(input, sum);
|
||||
// Create a pretty printing
|
||||
final StringBuilder output1 = new StringBuilder();
|
||||
pairs.forEach((pair) -> output1.append("{" + pair + ", " + (sum - pair) + "}, "));
|
||||
// Print result
|
||||
System.out.println("Traditional \"for\" loop: " + output1.toString().substring(0, output1.length() - 2));
|
||||
|
||||
/* Java 8 stream API */
|
||||
// Call the method
|
||||
pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
|
||||
// Create a pretty printing
|
||||
final StringBuilder output2 = new StringBuilder();
|
||||
pairs.forEach((pair) -> output2.append("{" + pair + ", " + (sum - pair) + "}, "));
|
||||
// Print result
|
||||
System.out.println("Java 8 streams API: " + output2.toString().substring(0, output2.length() - 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Print all different pairs for the given inputs: input array & sum number
|
||||
*/
|
||||
private static void getDifferentPairs(int[] input, int sum) {
|
||||
List<Integer> pairs = new ArrayList<>();
|
||||
System.out.println("~ All different pairs ~");
|
||||
|
||||
/* Traditional FOR loop */
|
||||
// Call method
|
||||
pairs = DifferentPairs.findPairsWithForLoop(input, sum);
|
||||
// Create a pretty printing
|
||||
final StringBuilder output3 = new StringBuilder();
|
||||
pairs.forEach((pair) -> output3.append("{" + pair + ", " + (sum - pair) + "}, "));
|
||||
// Print result
|
||||
System.out.println("Traditional \"for\" loop: " + output3.toString().substring(0, output3.length() - 2));
|
||||
|
||||
/* Java 8 stream API */
|
||||
// Call method
|
||||
pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
|
||||
// Create a pretty printing
|
||||
final StringBuilder output4 = new StringBuilder();
|
||||
pairs.forEach((pair) -> output4.append("{" + pair + ", " + (sum - pair) + "}, "));
|
||||
// Print result
|
||||
System.out.println("Java 8 streams API: " + output4.toString().substring(0, output4.length() - 2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.pow;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
|
||||
public class PowerExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int intResult = (int) Math.pow(2, 3);
|
||||
System.out.println("Math.pow(2, 3) = " + intResult);
|
||||
|
||||
double dblResult = Math.pow(4.2, 3);
|
||||
System.out.println("Math.pow(4.2, 3) = " + Math.pow(4.2, 3));
|
||||
|
||||
DecimalFormat df = new DecimalFormat(".00");
|
||||
System.out.println("Math.pow(4.2, 3) rounded = " + df.format(dblResult));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.prime;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PrimeGenerator {
|
||||
public static List<Integer> sieveOfEratosthenes(int n) {
|
||||
final boolean prime[] = new boolean[n + 1];
|
||||
Arrays.fill(prime, true);
|
||||
|
||||
for (int p = 2; p * p <= n; p++) {
|
||||
if (prime[p]) {
|
||||
for (int i = p * 2; i <= n; i += p)
|
||||
prime[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
final List<Integer> primes = new LinkedList<>();
|
||||
for (int i = 2; i <= n; i++) {
|
||||
if (prime[i])
|
||||
primes.add(i);
|
||||
}
|
||||
return primes;
|
||||
}
|
||||
|
||||
public static List<Integer> primeNumbersBruteForce(int max) {
|
||||
final List<Integer> primeNumbers = new LinkedList<Integer>();
|
||||
for (int i = 2; i <= max; i++) {
|
||||
if (isPrimeBruteForce(i)) {
|
||||
primeNumbers.add(i);
|
||||
}
|
||||
}
|
||||
return primeNumbers;
|
||||
}
|
||||
|
||||
private static boolean isPrimeBruteForce(int x) {
|
||||
for (int i = 2; i < x; i++) {
|
||||
if (x % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static List<Integer> primeNumbersTill(int max) {
|
||||
return IntStream.rangeClosed(2, max)
|
||||
.filter(x -> isPrime(x))
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static boolean isPrime(int x) {
|
||||
return IntStream.rangeClosed(2, (int) (Math.sqrt(x)))
|
||||
.allMatch(n -> x % n != 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
log4j.rootLogger=DEBUG, A1
|
||||
|
||||
log4j.appender.A1=org.apache.log4j.ConsoleAppender
|
||||
|
||||
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PrimeCheckerUnitTest {
|
||||
|
||||
private final BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenCheckIsPrime_thenTrue() {
|
||||
assertTrue(primeChecker.isPrime(13l));
|
||||
assertTrue(primeChecker.isPrime(1009L));
|
||||
assertTrue(primeChecker.isPrime(74207281L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckIsPrime_thenFalse() {
|
||||
assertTrue(!primeChecker.isPrime(50L));
|
||||
assertTrue(!primeChecker.isPrime(1001L));
|
||||
assertTrue(!primeChecker.isPrime(74207282L));
|
||||
}
|
||||
|
||||
private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenBFCheckIsPrime_thenTrue() {
|
||||
assertTrue(bfPrimeChecker.isPrime(13));
|
||||
assertTrue(bfPrimeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBFCheckIsPrime_thenFalse() {
|
||||
assertFalse(bfPrimeChecker.isPrime(50));
|
||||
assertFalse(bfPrimeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
private final OptimisedPrimeChecker optimisedPrimeChecker = new OptimisedPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenOptCheckIsPrime_thenTrue() {
|
||||
assertTrue(optimisedPrimeChecker.isPrime(13));
|
||||
assertTrue(optimisedPrimeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOptCheckIsPrime_thenFalse() {
|
||||
assertFalse(optimisedPrimeChecker.isPrime(50));
|
||||
assertFalse(optimisedPrimeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
private final PrimesPrimeChecker primesPrimeChecker = new PrimesPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenPrimesCheckIsPrime_thenTrue() {
|
||||
assertTrue(primesPrimeChecker.isPrime(13));
|
||||
assertTrue(primesPrimeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrimesCheckIsPrime_thenFalse() {
|
||||
assertFalse(primesPrimeChecker.isPrime(50));
|
||||
assertFalse(primesPrimeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
public class BigDecimalImplUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||
BigDecimal serviceTax = new BigDecimal("56.0084578639");
|
||||
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
|
||||
|
||||
BigDecimal entertainmentTax = new BigDecimal("23.00689");
|
||||
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
|
||||
|
||||
BigDecimal totalTax = serviceTax.add(entertainmentTax);
|
||||
BigDecimal result = BigDecimal.valueOf(79.01);
|
||||
|
||||
Assert.assertEquals(result, totalTax);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerImplUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
|
||||
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
|
||||
|
||||
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
|
||||
BigInteger result = new BigInteger("14110718640342675608722521633212952");
|
||||
|
||||
Assert.assertEquals(result, totalStars);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FloatingPointArithmeticUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
|
||||
double a = 13.22;
|
||||
double b = 4.88;
|
||||
double c = 21.45;
|
||||
double result = 39.55;
|
||||
|
||||
double abc = a + b + c;
|
||||
double acb = a + c + b;
|
||||
|
||||
Assert.assertEquals(result, abc, 0);
|
||||
Assert.assertNotEquals(result, acb, 0);
|
||||
|
||||
double ab = 18.1;
|
||||
double ac = 34.67;
|
||||
|
||||
double ab_c = ab + c;
|
||||
double ac_b = ac + b;
|
||||
|
||||
Assert.assertEquals(result, ab_c, 0);
|
||||
Assert.assertNotEquals(result, ac_b, 0);
|
||||
|
||||
BigDecimal d = new BigDecimal(String.valueOf(a));
|
||||
BigDecimal e = new BigDecimal(String.valueOf(b));
|
||||
BigDecimal f = new BigDecimal(String.valueOf(c));
|
||||
BigDecimal sum = new BigDecimal("39.55");
|
||||
|
||||
BigDecimal def = d.add(e).add(f);
|
||||
BigDecimal dfe = d.add(f).add(e);
|
||||
|
||||
Assert.assertEquals(0, def.compareTo(sum));
|
||||
Assert.assertEquals(0, dfe.compareTo(sum));
|
||||
|
||||
Assert.assertNotEquals(0, sum.compareTo(new BigDecimal(String.valueOf(acb))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import org.apache.commons.math3.util.Precision;
|
||||
import org.decimal4j.util.DoubleRounder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUnitTest {
|
||||
private double value = 2.03456d;
|
||||
private int places = 2;
|
||||
private double delta = 0.0d;
|
||||
private double expected = 2.03d;
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
|
||||
|
||||
places = 3;
|
||||
expected = 2.035d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
|
||||
|
||||
value = 1000.0d;
|
||||
places = 17;
|
||||
expected = 1000.0d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
|
||||
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 !
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
|
||||
|
||||
value = 256.025d;
|
||||
places = 2;
|
||||
expected = 256.03d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 !
|
||||
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 !
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 !
|
||||
|
||||
value = 260.775d;
|
||||
places = 2;
|
||||
expected = 260.78d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 !
|
||||
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 !
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 !
|
||||
|
||||
value = 90080070060.1d;
|
||||
places = 9;
|
||||
expected = 90080070060.1d;
|
||||
|
||||
Assert.assertEquals(expected, Round.round(value, places), delta);
|
||||
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
|
||||
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 !
|
||||
Assert.assertEquals(expected, Precision.round(value, places), delta);
|
||||
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Assume;
|
||||
import org.junit.experimental.theories.DataPoints;
|
||||
import org.junit.experimental.theories.Theories;
|
||||
import org.junit.experimental.theories.Theory;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
@RunWith(Theories.class)
|
||||
public class NumberOfDigitsIntegrationTest {
|
||||
|
||||
private static NumberOfDigits numberOfDigits;
|
||||
|
||||
static {
|
||||
numberOfDigits = new NumberOfDigits();
|
||||
}
|
||||
|
||||
@DataPoints
|
||||
public static int[][] lowestIntegers()
|
||||
{
|
||||
return new int[][]{
|
||||
{1, 1},
|
||||
{2, 10},
|
||||
{3, 100},
|
||||
{4, 1000},
|
||||
{5, 10000},
|
||||
{6, 100000},
|
||||
{7, 1000000},
|
||||
{8, 10000000},
|
||||
{9, 100000000},
|
||||
{10, 1000000000}
|
||||
};
|
||||
}
|
||||
|
||||
@DataPoints
|
||||
public static int[][] highestIntegers()
|
||||
{
|
||||
return new int[][]{
|
||||
{1, 9},
|
||||
{2, 99},
|
||||
{3, 999},
|
||||
{4, 9999},
|
||||
{5, 99999},
|
||||
{6, 999999},
|
||||
{7, 9999999},
|
||||
{8, 99999999},
|
||||
{9, 999999999},
|
||||
{10, Integer.MAX_VALUE}
|
||||
};
|
||||
}
|
||||
|
||||
@DataPoints
|
||||
public static int[][] randomIntegers()
|
||||
{
|
||||
return new int[][]{
|
||||
{1, 1},
|
||||
{2, 14},
|
||||
{3, 549},
|
||||
{4, 1136},
|
||||
{5, 25340},
|
||||
{6, 134321},
|
||||
{7, 1435432},
|
||||
{8, 54234129},
|
||||
{9, 113683912},
|
||||
{10, 1534031982}
|
||||
};
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenStringBasedSolutionInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.stringBasedSolution(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenLogarithmicApproachInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.logarithmicApproach(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenRepeatedMultiplicationInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.repeatedMultiplication(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenShiftOperatorsInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.shiftOperators(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenDividingWithPowersOf2Invoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.dividingWithPowersOf2(entry[1]));
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void givenDataPoints_whenDivideAndConquerInvoked_thenAllPointsMatch(final int[] entry) {
|
||||
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
|
||||
Assert.assertEquals(entry[0], numberOfDigits.divideAndConquer(entry[1]));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.pairsaddupnumber;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class DifferentPairsUnitTest {
|
||||
|
||||
/* All different pairs */
|
||||
|
||||
@Test
|
||||
public void whenTraditionalLoop_thenReturnAllDifferentPairs() {
|
||||
/* Data */
|
||||
final int[] input = {2, 4, 3, 3, 8};
|
||||
final int sum = 6;
|
||||
/* Call service */
|
||||
final List<Integer> pairs = DifferentPairs.findPairsWithForLoop(input, sum);
|
||||
/* Check results */
|
||||
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStreamApi_thenReturnAllDifferentPairs() {
|
||||
/* Data */
|
||||
final int[] input = {2, 4, 3, 3, 8};
|
||||
final int sum = 6;
|
||||
/* Call service */
|
||||
final List<Integer> pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
|
||||
/* Check results */
|
||||
assertNotNull(pairs);
|
||||
assertEquals(pairs.size(),2);
|
||||
assertEquals(pairs.get(0), new Integer(4));
|
||||
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.pairsaddupnumber;
|
||||
|
||||
import org.junit.Test;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class ExistingPairsUnitTest {
|
||||
|
||||
/* All existing pairs */
|
||||
|
||||
@Test
|
||||
public void whenTraditionalLoop_thenReturnAllExistingPairs() {
|
||||
/* Data */
|
||||
final int[] input = {2, 4, 3, 3, 8};
|
||||
final int sum = 6;
|
||||
/* Call service */
|
||||
final List<Integer> pairs = ExistingPairs.findPairsWithForLoop(input, sum);
|
||||
/* Check results */
|
||||
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStreamApi_thenReturnAllExistingPairs() {
|
||||
/* Data */
|
||||
final int[] input = {2, 4, 3, 3, 8};
|
||||
final int sum = 6;
|
||||
/* Call service */
|
||||
final List<Integer> pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
|
||||
/* Check results */
|
||||
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.prime;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.baeldung.prime.PrimeGenerator.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PrimeGeneratorUnitTest {
|
||||
@Test
|
||||
public void whenBruteForced_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = primeNumbersBruteForce(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOptimized_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = primeNumbersTill(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSieveOfEratosthenes_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = sieveOfEratosthenes(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.math3.random.RandomDataGenerator;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class JavaRandomUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
|
||||
|
||||
// tests - random long
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() {
|
||||
final long generatedLong = new Random().nextLong();
|
||||
|
||||
LOG.debug("{}", generatedLong);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
|
||||
final long generatedLong = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextLong();
|
||||
|
||||
LOG.debug("{}", generatedLong);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomLongBounded_thenCorrect() {
|
||||
final long leftLimit = 1L;
|
||||
final long rightLimit = 10L;
|
||||
final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit));
|
||||
|
||||
LOG.debug("{}", generatedLong);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApacheCommons_whenGeneratingRandomLongBounded_thenCorrect() {
|
||||
final long leftLimit = 10L;
|
||||
final long rightLimit = 100L;
|
||||
final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit);
|
||||
|
||||
LOG.debug("{}", generatedLong);
|
||||
}
|
||||
|
||||
// tests - random int
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
|
||||
final int generatedInteger = new Random().nextInt();
|
||||
|
||||
LOG.debug("{}", generatedInteger);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomIntegerBounded_thenCorrect() {
|
||||
final int leftLimit = 1;
|
||||
final int rightLimit = 10;
|
||||
final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
|
||||
|
||||
LOG.debug("{}", generatedInteger);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
|
||||
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextInt();
|
||||
|
||||
LOG.debug("{}", generatedInteger);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomIntegerBounded_thenCorrect() {
|
||||
final int leftLimit = 1;
|
||||
final int rightLimit = 10;
|
||||
final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit);
|
||||
|
||||
LOG.debug("{}", generatedInteger);
|
||||
}
|
||||
|
||||
// tests - random float
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() {
|
||||
final float generatedFloat = new Random().nextFloat();
|
||||
|
||||
LOG.debug("{}", generatedFloat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
|
||||
final float generatedFloat = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextFloat();
|
||||
|
||||
LOG.debug("{}", generatedFloat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomFloatBouned_thenCorrect() {
|
||||
final float leftLimit = 1F;
|
||||
final float rightLimit = 10F;
|
||||
final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit);
|
||||
|
||||
LOG.debug("{}", generatedFloat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
|
||||
final float leftLimit = 1F;
|
||||
final float rightLimit = 10F;
|
||||
final float randomFloat = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextFloat();
|
||||
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
|
||||
|
||||
LOG.debug("{}", generatedFloat);
|
||||
}
|
||||
|
||||
// tests - random double
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
|
||||
final double generatedDouble = Math.random();
|
||||
|
||||
LOG.debug("{}", generatedDouble);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
|
||||
final double generatedDouble = new RandomDataGenerator().getRandomGenerator()
|
||||
.nextDouble();
|
||||
|
||||
LOG.debug("{}", generatedDouble);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomDoubleBounded_thenCorrect() {
|
||||
final double leftLimit = 1D;
|
||||
final double rightLimit = 10D;
|
||||
final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit);
|
||||
|
||||
LOG.debug("{}", generatedDouble);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomDoubleBounded_thenCorrect() {
|
||||
final double leftLimit = 1D;
|
||||
final double rightLimit = 100D;
|
||||
final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit);
|
||||
|
||||
LOG.debug("{}", generatedDouble);
|
||||
}
|
||||
|
||||
// tests - random String
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
|
||||
final byte[] array = new byte[7]; // length is bounded by 7
|
||||
new Random().nextBytes(array);
|
||||
final String generatedString = new String(array, Charset.forName("UTF-8"));
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
final int leftLimit = 97; // letter 'a'
|
||||
final int rightLimit = 122; // letter 'z'
|
||||
final int targetStringLength = 10;
|
||||
final Random random = new Random();
|
||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
final String generatedString = buffer.toString();
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.random(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.randomAlphabetic(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.randomAlphanumeric(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
final int length = 10;
|
||||
final boolean useLetters = true;
|
||||
final boolean useNumbers = false;
|
||||
final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user