BAEL-1889 - Let's move the Java Number articles into a new module (#4619)
* BAEL-1849 - Convert from String to Date in Java * BAEL-1863 - Calling Callbacks with Mockito * BAEL-1889 - Let's move the Java Number articles into a new module * BAEL-1889 - Let's move the Java Number articles into a new module
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
de2afd7da8
commit
b44883b364
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 );
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
47
java-numbers/src/main/java/com/baeldung/maths/Round.java
Normal file
47
java-numbers/src/main/java/com/baeldung/maths/Round.java
Normal file
@@ -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;
|
||||
}
|
||||
}
|
||||
81
java-numbers/src/main/java/com/baeldung/nan/NaNExample.java
Normal file
81
java-numbers/src/main/java/com/baeldung/nan/NaNExample.java
Normal file
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
67
java-numbers/src/main/java/com/baeldung/numberofdigits/Benchmarking.java
Executable file
67
java-numbers/src/main/java/com/baeldung/numberofdigits/Benchmarking.java
Executable file
@@ -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);
|
||||
}
|
||||
}
|
||||
97
java-numbers/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java
Executable file
97
java-numbers/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java
Executable file
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
6
java-numbers/src/main/resources/log4j.properties
Normal file
6
java-numbers/src/main/resources/log4j.properties
Normal file
@@ -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
|
||||
13
java-numbers/src/main/resources/logback.xml
Normal file
13
java-numbers/src/main/resources/logback.xml
Normal file
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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