JAVA-12099 moved java-numbers modules to core-java-modules
This commit is contained in:
16
core-java-modules/java-numbers-2/README.md
Normal file
16
core-java-modules/java-numbers-2/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
## Java Number Cookbooks and Examples
|
||||
|
||||
This module contains articles about numbers in Java.
|
||||
|
||||
### Relevant Articles
|
||||
- [Lossy Conversion in Java](https://www.baeldung.com/java-lossy-conversion)
|
||||
- [A Guide to the Java Math Class](https://www.baeldung.com/java-lang-math)
|
||||
- [Calculate the Area of a Circle in Java](https://www.baeldung.com/java-calculate-circle-area)
|
||||
- [NaN in Java](https://www.baeldung.com/java-not-a-number)
|
||||
- [Generating Prime Numbers in Java](https://www.baeldung.com/java-generate-prime-numbers)
|
||||
- [Using Math.pow in Java](https://www.baeldung.com/java-math-pow)
|
||||
- [Check If a Number Is Prime in Java](https://www.baeldung.com/java-prime-numbers)
|
||||
- [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers)
|
||||
- [Finding the Least Common Multiple in Java](https://www.baeldung.com/java-least-common-multiple)
|
||||
- [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers)
|
||||
- More articles: [[<-- prev]](/java-numbers) [[next -->]](/java-numbers-3)
|
||||
44
core-java-modules/java-numbers-2/pom.xml
Normal file
44
core-java-modules/java-numbers-2/pom.xml
Normal file
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>java-numbers-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>java-numbers-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>dsiutils</artifactId>
|
||||
<version>${dsiutils.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-numbers-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<dsiutils.version>2.6.0</dsiutils.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -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 > 1 ? 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 > 1 ? 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,26 @@
|
||||
package com.baeldung.area.circle;
|
||||
|
||||
public class Circle {
|
||||
|
||||
private double radius;
|
||||
|
||||
public Circle(double radius) {
|
||||
this.radius = radius;
|
||||
}
|
||||
|
||||
public double getRadius() {
|
||||
return radius;
|
||||
}
|
||||
|
||||
public void setRadius(double radius) {
|
||||
this.radius = radius;
|
||||
}
|
||||
|
||||
private double calculateArea() {
|
||||
return radius * radius * Math.PI;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "The area of the circle [radius = " + radius + "]: " + calculateArea();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.area.circle;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class CircleArea {
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length > 0) {
|
||||
try {
|
||||
double radius = Double.parseDouble(args[0]);
|
||||
calculateArea(radius);
|
||||
} catch (NumberFormatException nfe) {
|
||||
System.out.println("Invalid value for radius");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
try (Scanner scanner = new Scanner(System.in)) {
|
||||
System.out.println("Please enter radius value: ");
|
||||
double radius = scanner.nextDouble();
|
||||
calculateArea(radius);
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Invalid value for radius");
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
Circle circle = new Circle(7);
|
||||
System.out.println(circle);
|
||||
}
|
||||
|
||||
private static void calculateArea(double radius) {
|
||||
double area = radius * radius * Math.PI;
|
||||
System.out.println("The area of the circle [radius = " + radius + "]: " + area);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.baeldung.binarynumbers;
|
||||
|
||||
public class BinaryNumbers {
|
||||
|
||||
/**
|
||||
* This method takes a decimal number and convert it into a binary number.
|
||||
* example:- input:10, output:1010
|
||||
*
|
||||
* @param decimalNumber
|
||||
* @return binary number
|
||||
*/
|
||||
public Integer convertDecimalToBinary(Integer decimalNumber) {
|
||||
|
||||
if (decimalNumber == 0) {
|
||||
return decimalNumber;
|
||||
}
|
||||
|
||||
StringBuilder binaryNumber = new StringBuilder();
|
||||
Integer quotient = decimalNumber;
|
||||
|
||||
while (quotient > 0) {
|
||||
|
||||
int remainder = quotient % 2;
|
||||
binaryNumber.append(remainder);
|
||||
quotient /= 2;
|
||||
}
|
||||
|
||||
binaryNumber = binaryNumber.reverse();
|
||||
return Integer.valueOf(binaryNumber.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes a binary number and convert it into a decimal number.
|
||||
* example:- input:101, output:5
|
||||
*
|
||||
* @param binary number
|
||||
* @return decimal Number
|
||||
*/
|
||||
public Integer convertBinaryToDecimal(Integer binaryNumber) {
|
||||
|
||||
Integer decimalNumber = 0;
|
||||
Integer base = 1;
|
||||
|
||||
while (binaryNumber > 0) {
|
||||
|
||||
int lastDigit = binaryNumber % 10;
|
||||
binaryNumber = binaryNumber / 10;
|
||||
|
||||
decimalNumber += lastDigit * base;
|
||||
base = base * 2;
|
||||
}
|
||||
return decimalNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method accepts two binary numbers and returns sum of input numbers.
|
||||
* Example:- firstNum: 101, secondNum: 100, output: 1001
|
||||
*
|
||||
* @param firstNum
|
||||
* @param secondNum
|
||||
* @return addition of input numbers
|
||||
*/
|
||||
public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
|
||||
int carry = 0;
|
||||
int temp;
|
||||
|
||||
while (firstNum != 0 || secondNum != 0) {
|
||||
|
||||
temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
|
||||
output.append(temp);
|
||||
|
||||
carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
|
||||
|
||||
firstNum = firstNum / 10;
|
||||
secondNum = secondNum / 10;
|
||||
}
|
||||
|
||||
if (carry != 0) {
|
||||
output.append(carry);
|
||||
}
|
||||
|
||||
return Integer.valueOf(output.reverse()
|
||||
.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes two binary number as input and subtract second number from the first number.
|
||||
* example:- firstNum: 1000, secondNum: 11, output: 101
|
||||
* @param firstNum
|
||||
* @param secondNum
|
||||
* @return Result of subtraction of secondNum from first
|
||||
*/
|
||||
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||
|
||||
int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
|
||||
StringBuilder output = new StringBuilder();
|
||||
int carry = 0;
|
||||
int temp;
|
||||
|
||||
while (firstNum != 0 || onesComplement != 0) {
|
||||
|
||||
temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
|
||||
output.append(temp);
|
||||
|
||||
carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
|
||||
|
||||
firstNum = firstNum / 10;
|
||||
onesComplement = onesComplement / 10;
|
||||
}
|
||||
|
||||
String additionOfFirstNumAndOnesComplement = output.reverse()
|
||||
.toString();
|
||||
|
||||
if (carry == 1) {
|
||||
return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
|
||||
} else {
|
||||
return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
|
||||
}
|
||||
}
|
||||
|
||||
public Integer getOnesComplement(Integer num) {
|
||||
|
||||
StringBuilder onesComplement = new StringBuilder();
|
||||
while (num > 0) {
|
||||
int lastDigit = num % 10;
|
||||
if (lastDigit == 0) {
|
||||
onesComplement.append(1);
|
||||
} else {
|
||||
onesComplement.append(0);
|
||||
}
|
||||
num = num / 10;
|
||||
}
|
||||
return Integer.valueOf(onesComplement.reverse()
|
||||
.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.lcm;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerLCM {
|
||||
|
||||
public static BigInteger lcm(BigInteger number1, BigInteger number2) {
|
||||
BigInteger gcd = number1.gcd(number2);
|
||||
BigInteger absProduct = number1.multiply(number2).abs();
|
||||
return absProduct.divide(gcd);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.lcm;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class EuclideanAlgorithm {
|
||||
|
||||
public static int gcd(int number1, int number2) {
|
||||
if (number1 == 0 || number2 == 0) {
|
||||
return number1 + number2;
|
||||
} else {
|
||||
int absNumber1 = Math.abs(number1);
|
||||
int absNumber2 = Math.abs(number2);
|
||||
int biggerValue = Math.max(absNumber1, absNumber2);
|
||||
int smallerValue = Math.min(absNumber1, absNumber2);
|
||||
return gcd(biggerValue % smallerValue, smallerValue);
|
||||
}
|
||||
}
|
||||
|
||||
public static int lcm(int number1, int number2) {
|
||||
if (number1 == 0 || number2 == 0)
|
||||
return 0;
|
||||
else {
|
||||
int gcd = gcd(number1, number2);
|
||||
return Math.abs(number1 * number2) / gcd;
|
||||
}
|
||||
}
|
||||
|
||||
public static int lcmForArray(int[] numbers) {
|
||||
int lcm = numbers[0];
|
||||
for (int i = 1; i <= numbers.length - 1; i++) {
|
||||
lcm = lcm(lcm, numbers[i]);
|
||||
}
|
||||
return lcm;
|
||||
}
|
||||
|
||||
public static int lcmByLambda(int... numbers) {
|
||||
return Arrays.stream(numbers).reduce(1, (lcmSoFar, currentNumber) -> Math.abs(lcmSoFar * currentNumber) / gcd(lcmSoFar, currentNumber));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.lcm;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class PrimeFactorizationAlgorithm {
|
||||
|
||||
public static Map<Integer, Integer> getPrimeFactors(int number) {
|
||||
int absNumber = Math.abs(number);
|
||||
Map<Integer, Integer> primeFactorsMap = new HashMap<Integer, Integer>();
|
||||
for (int factor = 2; factor <= absNumber; factor++) {
|
||||
while (absNumber % factor == 0) {
|
||||
Integer power = primeFactorsMap.get(factor);
|
||||
if (power == null) {
|
||||
power = 0;
|
||||
}
|
||||
primeFactorsMap.put(factor, power + 1);
|
||||
absNumber /= factor;
|
||||
}
|
||||
}
|
||||
return primeFactorsMap;
|
||||
}
|
||||
|
||||
public static int lcm(int number1, int number2) {
|
||||
if (number1 == 0 || number2 == 0) {
|
||||
return 0;
|
||||
}
|
||||
Map<Integer, Integer> primeFactorsForNum1 = getPrimeFactors(number1);
|
||||
Map<Integer, Integer> primeFactorsForNum2 = getPrimeFactors(number2);
|
||||
Set<Integer> primeFactorsUnionSet = new HashSet<Integer>(primeFactorsForNum1.keySet());
|
||||
primeFactorsUnionSet.addAll(primeFactorsForNum2.keySet());
|
||||
int lcm = 1;
|
||||
for (Integer primeFactor : primeFactorsUnionSet) {
|
||||
lcm *= Math.pow(primeFactor, Math.max(primeFactorsForNum1.getOrDefault(primeFactor, 0),
|
||||
primeFactorsForNum2.getOrDefault(primeFactor, 0)));
|
||||
}
|
||||
return lcm;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.lcm;
|
||||
|
||||
public class SimpleAlgorithm {
|
||||
public static int lcm(int number1, int number2) {
|
||||
if (number1 == 0 || number2 == 0) {
|
||||
return 0;
|
||||
}
|
||||
int absNumber1 = Math.abs(number1);
|
||||
int absNumber2 = Math.abs(number2);
|
||||
int absHigherNumber = Math.max(absNumber1, absNumber2);
|
||||
int absLowerNumber = Math.min(absNumber1, absNumber2);
|
||||
int lcm = absHigherNumber;
|
||||
while (lcm % absLowerNumber != 0) {
|
||||
lcm += absHigherNumber;
|
||||
}
|
||||
return lcm;
|
||||
}
|
||||
}
|
||||
@@ -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,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,72 @@
|
||||
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(2L));
|
||||
assertTrue(primeChecker.isPrime(13L));
|
||||
assertTrue(primeChecker.isPrime(1009L));
|
||||
assertTrue(primeChecker.isPrime(74207281L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckIsPrime_thenFalse() {
|
||||
assertFalse(primeChecker.isPrime(50L));
|
||||
assertFalse(primeChecker.isPrime(1001L));
|
||||
assertFalse(primeChecker.isPrime(74207282L));
|
||||
}
|
||||
|
||||
private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenBFCheckIsPrime_thenTrue() {
|
||||
assertTrue(bfPrimeChecker.isPrime(2));
|
||||
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(2));
|
||||
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(2));
|
||||
assertTrue(primesPrimeChecker.isPrime(13));
|
||||
assertTrue(primesPrimeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrimesCheckIsPrime_thenFalse() {
|
||||
assertFalse(primesPrimeChecker.isPrime(50));
|
||||
assertFalse(primesPrimeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.binarynumbers;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinaryNumbersUnitTest {
|
||||
|
||||
private BinaryNumbers binaryNumbers = new BinaryNumbers();
|
||||
|
||||
@Test
|
||||
public void given_decimalNumber_then_returnBinaryNumber() {
|
||||
assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8));
|
||||
assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_decimalNumber_then_convertToBinaryNumber() {
|
||||
assertEquals("1000", Integer.toBinaryString(8));
|
||||
assertEquals("10100", Integer.toBinaryString(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryNumber_then_ConvertToDecimalNumber() {
|
||||
assertEquals(8, Integer.parseInt("1000", 2));
|
||||
assertEquals(20, Integer.parseInt("10100", 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryNumber_then_returnDecimalNumber() {
|
||||
assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000));
|
||||
assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_twoBinaryNumber_then_returnAddition() {
|
||||
// adding 4 and 10
|
||||
assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010));
|
||||
|
||||
// adding 26 and 14
|
||||
assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_twoBinaryNumber_then_returnSubtraction() {
|
||||
// subtracting 16 from 25
|
||||
assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000));
|
||||
|
||||
// subtracting 29 from 16, the output here is negative
|
||||
assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryLiteral_thenReturnDecimalValue() {
|
||||
|
||||
byte five = 0b101;
|
||||
assertEquals((byte) 5, five);
|
||||
|
||||
short three = 0b11;
|
||||
assertEquals((short) 3, three);
|
||||
|
||||
int nine = 0B1001;
|
||||
assertEquals(9, nine);
|
||||
|
||||
long twentyNine = 0B11101;
|
||||
assertEquals(29, twentyNine);
|
||||
|
||||
int minusThirtySeven = -0B100101;
|
||||
assertEquals(-37, minusThirtySeven);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package com.baeldung.java.math;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MathUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAbsInteger_thenReturnAbsoluteValue() {
|
||||
assertEquals(5,Math.abs(-5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMaxBetweenTwoValue_thenReturnMaximum() {
|
||||
assertEquals(10, Math.max(5,10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMinBetweenTwoValue_thenReturnMinimum() {
|
||||
assertEquals(5, Math.min(5,10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSignumWithNegativeNumber_thenReturnMinusOne() {
|
||||
assertEquals(-1, Math.signum(-5), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCopySignWithNegativeSign_thenReturnNegativeArgument() {
|
||||
assertEquals(-5, Math.copySign(5,-1), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPow_thenReturnPoweredValue() {
|
||||
assertEquals(25, Math.pow(5,2),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSqrt_thenReturnSquareRoot() {
|
||||
assertEquals(5, Math.sqrt(25),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCbrt_thenReturnCubeRoot() {
|
||||
assertEquals(5, Math.cbrt(125),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExp_thenReturnEulerNumberRaised() {
|
||||
assertEquals(2.718, Math.exp(1),0.1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExpm1_thenReturnEulerNumberMinusOne() {
|
||||
assertEquals(1.718, Math.expm1(1),0.1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetExponent_thenReturnUnbiasedExponent() {
|
||||
assertEquals(8, Math.getExponent(333.3),0);
|
||||
assertEquals(7, Math.getExponent(222.2f),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog_thenReturnValue() {
|
||||
assertEquals(1, Math.log(Math.E),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog10_thenReturnValue() {
|
||||
assertEquals(1, Math.log10(10),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog1p_thenReturnValue() {
|
||||
assertEquals(1.31, Math.log1p(Math.E),0.1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSin_thenReturnValue() {
|
||||
assertEquals(1, Math.sin(Math.PI/2),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCos_thenReturnValue() {
|
||||
assertEquals(1, Math.cos(0),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTan_thenReturnValue() {
|
||||
assertEquals(1, Math.tan(Math.PI/4),0.1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAsin_thenReturnValue() {
|
||||
assertEquals(Math.PI/2, Math.asin(1),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAcos_thenReturnValue() {
|
||||
assertEquals(Math.PI/2, Math.acos(0),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAtan_thenReturnValue() {
|
||||
assertEquals(Math.PI/4, Math.atan(1),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAtan2_thenReturnValue() {
|
||||
assertEquals(Math.PI/4, Math.atan2(1,1),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToDegrees_thenReturnValue() {
|
||||
assertEquals(180, Math.toDegrees(Math.PI),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToRadians_thenReturnValue() {
|
||||
assertEquals(Math.PI, Math.toRadians(180),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCeil_thenReturnValue() {
|
||||
assertEquals(4, Math.ceil(Math.PI),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFloor_thenReturnValue() {
|
||||
assertEquals(3, Math.floor(Math.PI),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetExponent_thenReturnValue() {
|
||||
assertEquals(8, Math.getExponent(333.3),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIEEERemainder_thenReturnValue() {
|
||||
assertEquals(1.0, Math.IEEEremainder(5,2),0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNextAfter_thenReturnValue() {
|
||||
assertEquals(1.9499999284744263, Math.nextAfter(1.95f,1),0.0000001);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNextUp_thenReturnValue() {
|
||||
assertEquals(1.9500002, Math.nextUp(1.95f),0.0000001);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRint_thenReturnValue() {
|
||||
assertEquals(2.0, Math.rint(1.95f),0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRound_thenReturnValue() {
|
||||
assertEquals(2.0, Math.round(1.95f),0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenScalb_thenReturnValue() {
|
||||
assertEquals(48, Math.scalb(3, 4),0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHypot_thenReturnValue() {
|
||||
assertEquals(5, Math.hypot(4, 3),0.0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.lcm;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerLCMUnitTest {
|
||||
|
||||
@Test
|
||||
public void testLCM() {
|
||||
BigInteger number1 = new BigInteger("12");
|
||||
BigInteger number2 = new BigInteger("18");
|
||||
BigInteger expectedLCM = new BigInteger("36");
|
||||
Assert.assertEquals(expectedLCM, BigIntegerLCM.lcm(number1, number2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.lcm;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class EuclideanAlgorithmUnitTest {
|
||||
|
||||
@Test
|
||||
public void testGCD() {
|
||||
Assert.assertEquals(6, EuclideanAlgorithm.gcd(12, 18));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLCM() {
|
||||
Assert.assertEquals(36, EuclideanAlgorithm.lcm(12, 18));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLCMForArray() {
|
||||
Assert.assertEquals(15, EuclideanAlgorithm.lcmForArray(new int[]{3, 5, 15}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLCMByLambdaForArray() {
|
||||
Assert.assertEquals(15, EuclideanAlgorithm.lcmByLambda(new int[]{3, 5, 15}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.lcm;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.baeldung.lcm.PrimeFactorizationAlgorithm.*;
|
||||
|
||||
|
||||
public class PrimeFactorizationAlgorithmUnitTest {
|
||||
|
||||
@Test
|
||||
public void testGetPrimeFactors() {
|
||||
Map<Integer, Integer> expectedPrimeFactorsMapForTwelve = new HashMap<>();
|
||||
expectedPrimeFactorsMapForTwelve.put(2, 2);
|
||||
expectedPrimeFactorsMapForTwelve.put(3, 1);
|
||||
Map<Integer, Integer> expectedPrimeFactorsMapForEighteen = new HashMap<>();
|
||||
expectedPrimeFactorsMapForEighteen.put(2, 1);
|
||||
expectedPrimeFactorsMapForEighteen.put(3, 2);
|
||||
Assert.assertEquals(expectedPrimeFactorsMapForTwelve, getPrimeFactors(12));
|
||||
Assert.assertEquals(expectedPrimeFactorsMapForEighteen, getPrimeFactors(18));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLCM() {
|
||||
Assert.assertEquals(36, PrimeFactorizationAlgorithm.lcm(12, 18));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.lcm;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.baeldung.lcm.SimpleAlgorithm.*;
|
||||
|
||||
public class SimpleAlgorithmUnitTest {
|
||||
|
||||
@Test
|
||||
public void testLCM() {
|
||||
Assert.assertEquals(36, lcm(12, 18));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.lossyconversion;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ConversionTechniquesUnitTest {
|
||||
|
||||
@Test
|
||||
public void testPrimitiveConversion() {
|
||||
|
||||
long longNum = 24;
|
||||
short shortNum = (short) longNum;
|
||||
assertEquals(24, shortNum);
|
||||
|
||||
double doubleNum = 15.6;
|
||||
int integerNum = (int) doubleNum;
|
||||
assertEquals(15, integerNum);
|
||||
|
||||
long largeLongNum = 32768;
|
||||
short minShortNum = (short) largeLongNum;
|
||||
assertEquals(-32768, minShortNum);
|
||||
|
||||
long smallLongNum = -32769;
|
||||
short maxShortNum = (short) smallLongNum;
|
||||
assertEquals(32767, maxShortNum);
|
||||
|
||||
long maxLong = Long.MAX_VALUE;
|
||||
int minInt = (int) maxLong;
|
||||
assertEquals(-1, minInt);
|
||||
|
||||
long minLong = Long.MIN_VALUE;
|
||||
int maxInt = (int) minLong;
|
||||
assertEquals(0, maxInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrapperToPrimitiveConversion() {
|
||||
|
||||
Float floatNum = 17.564f;
|
||||
long longNum = floatNum.longValue();
|
||||
assertEquals(17, longNum);
|
||||
|
||||
Double doubleNum = 15.9999;
|
||||
longNum = doubleNum.longValue();
|
||||
assertEquals(15, longNum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrapperToPrimitiveConversionUsingMathRound() {
|
||||
|
||||
Double doubleNum = 15.9999;
|
||||
long longNum = Math.round(doubleNum);
|
||||
assertEquals(16, longNum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrapperConversion() {
|
||||
|
||||
Double doubleNum = 10.3;
|
||||
double dbl = doubleNum.doubleValue(); //unboxing
|
||||
int intgr = (int) dbl; //downcasting
|
||||
Integer intNum = Integer.valueOf(intgr);
|
||||
assertEquals(Integer.valueOf(10), intNum);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.prime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
17
core-java-modules/java-numbers-3/README.md
Normal file
17
core-java-modules/java-numbers-3/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
## Java Number Cookbooks and Examples
|
||||
|
||||
This module contains articles about numbers in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Generating Random Numbers in Java](https://www.baeldung.com/java-generating-random-numbers)
|
||||
- [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long)
|
||||
- [Check for null Before Calling Parse in Double.parseDouble](https://www.baeldung.com/java-check-null-parse-double)
|
||||
- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range)
|
||||
- [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range)
|
||||
- [Fibonacci Series in Java](https://www.baeldung.com/java-fibonacci)
|
||||
- [Guide to the Number Class in Java](https://www.baeldung.com/java-number-class)
|
||||
- [Print an Integer in Binary Format in Java](https://www.baeldung.com/java-print-integer-binary)
|
||||
- [Number Formatting in Java](https://www.baeldung.com/java-number-formatting)
|
||||
- [Division by Zero in Java: Exception, Infinity, or Not a Number](https://www.baeldung.com/java-division-by-zero)
|
||||
- More articles: [[<-- prev]](/java-numbers-2)
|
||||
49
core-java-modules/java-numbers-3/pom.xml
Normal file
49
core-java-modules/java-numbers-3/pom.xml
Normal file
@@ -0,0 +1,49 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>java-numbers-3</artifactId>
|
||||
<name>java-numbers-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>dsiutils</artifactId>
|
||||
<version>${dsiutils.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-numbers-3</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<dsiutils.version>2.6.0</dsiutils.version>
|
||||
<vavr.version>0.10.2</vavr.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.fibonacci;
|
||||
|
||||
public class FibonacciSeriesUtils {
|
||||
|
||||
public static int nthFibonacciTermRecursiveMethod(int n) {
|
||||
if (n == 0 || n == 1) {
|
||||
return n;
|
||||
}
|
||||
return nthFibonacciTermRecursiveMethod(n - 1) + nthFibonacciTermRecursiveMethod(n - 2);
|
||||
}
|
||||
|
||||
public static int nthFibonacciTermIterativeMethod(int n) {
|
||||
if (n == 0 || n == 1) {
|
||||
return n;
|
||||
}
|
||||
int n0 = 0, n1 = 1;
|
||||
int tempNthTerm;
|
||||
for (int i = 2; i <= n; i++) {
|
||||
tempNthTerm = n0 + n1;
|
||||
n0 = n1;
|
||||
n1 = tempNthTerm;
|
||||
}
|
||||
return n1;
|
||||
}
|
||||
|
||||
public static int nthFibonacciTermUsingBinetsFormula(int n) {
|
||||
final double squareRootOf5 = Math.sqrt(5);
|
||||
final double phi = (1 + squareRootOf5)/2;
|
||||
int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5);
|
||||
return nthTerm;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.formatNumber;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
public class FormatNumber {
|
||||
public static double withBigDecimal(double value, int places) {
|
||||
if (places < 0)
|
||||
throw new IllegalArgumentException();
|
||||
|
||||
BigDecimal bigDecimal = new BigDecimal(value);
|
||||
bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
|
||||
return bigDecimal.doubleValue();
|
||||
}
|
||||
|
||||
public static double withMathRound(double value, int places) {
|
||||
double scale = Math.pow(10, places);
|
||||
return Math.round(value * scale) / scale;
|
||||
}
|
||||
|
||||
public static double withDecimalFormatPattern(double value, int places) {
|
||||
DecimalFormat df2 = new DecimalFormat("#,###,###,##0.00");
|
||||
DecimalFormat df3 = new DecimalFormat("#,###,###,##0.000");
|
||||
if (places == 2)
|
||||
return new Double(df2.format(value));
|
||||
else if (places == 3)
|
||||
return new Double(df3.format(value));
|
||||
else
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
public static double withDecimalFormatLocal(double value) {
|
||||
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault());
|
||||
return new Double(df.format(value));
|
||||
}
|
||||
|
||||
public static String withStringFormat(double value, int places) {
|
||||
return String.format("%." + places + "f", value);
|
||||
}
|
||||
|
||||
public static String byPaddingZeros(int value, int paddingLength) {
|
||||
return String.format("%0" + paddingLength + "d", value);
|
||||
}
|
||||
|
||||
public static double withTwoDecimalPlaces(double value) {
|
||||
DecimalFormat df = new DecimalFormat("#.00");
|
||||
return new Double(df.format(value));
|
||||
}
|
||||
|
||||
public static String withLargeIntegers(double value) {
|
||||
DecimalFormat df = new DecimalFormat("###,###,###");
|
||||
return df.format(value);
|
||||
}
|
||||
|
||||
public static String forPercentages(double value, Locale localisation) {
|
||||
NumberFormat nf = NumberFormat.getPercentInstance(localisation);
|
||||
return nf.format(value);
|
||||
}
|
||||
|
||||
public static String currencyWithChosenLocalisation(double value, Locale localisation) {
|
||||
NumberFormat nf = NumberFormat.getCurrencyInstance(localisation);
|
||||
return nf.format(value);
|
||||
}
|
||||
|
||||
public static String currencyWithDefaultLocalisation(double value) {
|
||||
NumberFormat nf = NumberFormat.getCurrencyInstance();
|
||||
return nf.format(value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.integerToBinary;
|
||||
|
||||
public class IntegerToBinary {
|
||||
public static String convertIntegerToBinary(int n) {
|
||||
if(n == 0) {
|
||||
return "0";
|
||||
}
|
||||
StringBuilder binaryNumber = new StringBuilder();
|
||||
while (n > 0) {
|
||||
int remainder = n % 2;
|
||||
binaryNumber.append(remainder);
|
||||
n /= 2;
|
||||
}
|
||||
binaryNumber = binaryNumber.reverse();
|
||||
return binaryNumber.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.numbersinrange;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class NumbersInARange {
|
||||
|
||||
public List<Integer> getNumbersInRange(int start, int end) {
|
||||
List<Integer> result = new ArrayList<>();
|
||||
for (int i = start; i < end; i++) {
|
||||
result.add(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<Integer> getNumbersUsingIntStreamRange(int start, int end) {
|
||||
return IntStream.range(start, end)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Integer> getNumbersUsingIntStreamRangeClosed(int start, int end) {
|
||||
return IntStream.rangeClosed(start, end)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Integer> getNumbersUsingIntStreamIterate(int start, int limit) {
|
||||
return IntStream.iterate(start, i -> i + 1)
|
||||
.limit(limit)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.numbersinrange;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class RandomNumbersInARange {
|
||||
|
||||
public int getRandomNumber(int min, int max) {
|
||||
return (int) ((Math.random() * (max - min)) + min);
|
||||
}
|
||||
|
||||
public int getRandomNumberUsingNextInt(int min, int max) {
|
||||
Random random = new Random();
|
||||
return random.nextInt(max - min) + min;
|
||||
}
|
||||
|
||||
public int getRandomNumberUsingInts(int min, int max) {
|
||||
Random random = new Random();
|
||||
return random.ints(min, max)
|
||||
.findFirst()
|
||||
.getAsInt();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.baeldung.randomnumbers;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Random;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.apache.commons.math3.random.RandomDataGenerator;
|
||||
|
||||
import it.unimi.dsi.util.XoRoShiRo128PlusRandom;
|
||||
|
||||
public class RandomNumbersGenerator {
|
||||
|
||||
public Integer generateRandomWithMathRandom(int max, int min) {
|
||||
return (int) ((Math.random() * (max - min)) + min);
|
||||
}
|
||||
|
||||
public Integer generateRandomWithNextInt() {
|
||||
Random random = new Random();
|
||||
int randomWithNextInt = random.nextInt();
|
||||
return randomWithNextInt;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithNextIntWithinARange(int min, int max) {
|
||||
Random random = new Random();
|
||||
int randomWintNextIntWithinARange = random.nextInt(max - min) + min;
|
||||
return randomWintNextIntWithinARange;
|
||||
}
|
||||
|
||||
public IntStream generateRandomUnlimitedIntStream() {
|
||||
Random random = new Random();
|
||||
IntStream unlimitedIntStream = random.ints();
|
||||
return unlimitedIntStream;
|
||||
}
|
||||
|
||||
public IntStream generateRandomLimitedIntStream(long streamSize) {
|
||||
Random random = new Random();
|
||||
IntStream limitedIntStream = random.ints(streamSize);
|
||||
return limitedIntStream;
|
||||
}
|
||||
|
||||
public IntStream generateRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) {
|
||||
Random random = new Random();
|
||||
IntStream limitedIntStreamWithinARange = random.ints(streamSize, min, max);
|
||||
return limitedIntStreamWithinARange;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithThreadLocalRandom() {
|
||||
int randomWithThreadLocalRandom = ThreadLocalRandom.current()
|
||||
.nextInt();
|
||||
return randomWithThreadLocalRandom;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithThreadLocalRandomInARange(int min, int max) {
|
||||
int randomWithThreadLocalRandomInARange = ThreadLocalRandom.current()
|
||||
.nextInt(min, max);
|
||||
return randomWithThreadLocalRandomInARange;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithThreadLocalRandomFromZero(int max) {
|
||||
int randomWithThreadLocalRandomFromZero = ThreadLocalRandom.current()
|
||||
.nextInt(max);
|
||||
return randomWithThreadLocalRandomFromZero;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithSplittableRandom(int min, int max) {
|
||||
SplittableRandom splittableRandom = new SplittableRandom();
|
||||
int randomWithSplittableRandom = splittableRandom.nextInt(min, max);
|
||||
return randomWithSplittableRandom;
|
||||
}
|
||||
|
||||
public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) {
|
||||
SplittableRandom splittableRandom = new SplittableRandom();
|
||||
IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max);
|
||||
return limitedIntStreamWithinARangeWithSplittableRandom;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithSecureRandom() {
|
||||
SecureRandom secureRandom = new SecureRandom();
|
||||
int randomWithSecureRandom = secureRandom.nextInt();
|
||||
return randomWithSecureRandom;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithSecureRandomWithinARange(int min, int max) {
|
||||
SecureRandom secureRandom = new SecureRandom();
|
||||
int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min;
|
||||
return randomWithSecureRandomWithinARange;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithRandomDataGenerator(int min, int max) {
|
||||
RandomDataGenerator randomDataGenerator = new RandomDataGenerator();
|
||||
int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max);
|
||||
return randomWithRandomDataGenerator;
|
||||
}
|
||||
|
||||
public Integer generateRandomWithXoRoShiRo128PlusRandom(int min, int max) {
|
||||
XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom();
|
||||
int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max - min) + min;
|
||||
return randomWithXoRoShiRo128PlusRandom;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.abstractnumber;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AbstractNumberUnitTest {
|
||||
|
||||
private final static double DOUBLE_VALUE = 9999.999;
|
||||
private final static float FLOAT_VALUE = 101.99F;
|
||||
private final static long LONG_VALUE = 1000L;
|
||||
private final static int INTEGER_VALUE = 100;
|
||||
private final static short SHORT_VALUE = 127;
|
||||
private final static byte BYTE_VALUE = 120;
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenShortValueUsed_thenShortValueReturned() {
|
||||
Double doubleValue = Double.valueOf(DOUBLE_VALUE);
|
||||
assertEquals(9999, doubleValue.shortValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFloatValue_whenByteValueUsed_thenByteValueReturned() {
|
||||
Float floatValue = Float.valueOf(FLOAT_VALUE);
|
||||
assertEquals(101, floatValue.byteValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLongValue_whenInitValueUsed_thenInitValueReturned() {
|
||||
Long longValue = Long.valueOf(LONG_VALUE);
|
||||
assertEquals(1000, longValue.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerValue_whenLongValueUsed_thenLongValueReturned() {
|
||||
Integer integerValue = Integer.valueOf(INTEGER_VALUE);
|
||||
assertEquals(100, integerValue.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShortValue_whenFloatValueUsed_thenFloatValueReturned() {
|
||||
Short shortValue = Short.valueOf(SHORT_VALUE);
|
||||
assertEquals(127.0F, shortValue.floatValue(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteValue_whenDoubleValueUsed_thenDoubleValueReturned() {
|
||||
Byte byteValue = Byte.valueOf(BYTE_VALUE);
|
||||
assertEquals(120.0, byteValue.doubleValue(), 0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.divisionbyzero;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class DivisionByZeroUnitTest {
|
||||
|
||||
@Test
|
||||
void givenInt_whenDividedByZero_thenThrowException() {
|
||||
assertThrows(ArithmeticException.class, () -> {
|
||||
int result = 12 / 0;
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenDividingIntZeroByZero_thenThrowException() {
|
||||
assertThrows(ArithmeticException.class, () -> {
|
||||
int result = 0 / 0;
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenDividingFloatingNumberByZero_thenNoExceptionIsThrown() {
|
||||
assertDoesNotThrow(() -> {
|
||||
float result = 0f / 0;
|
||||
});
|
||||
assertDoesNotThrow(() -> {
|
||||
double result = 0d / 0;
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPositiveFloatingNumber_whenDividedByZero_thenReturnPositiveInfinity() {
|
||||
assertEquals(Float.POSITIVE_INFINITY, 12f / 0);
|
||||
assertEquals(Double.POSITIVE_INFINITY, 12d / 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNegativeFloatingNumber_whenDividedByZero_thenReturnNegativeInfinity() {
|
||||
assertEquals(Float.NEGATIVE_INFINITY, -12f / 0);
|
||||
assertEquals(Double.NEGATIVE_INFINITY, -12d / 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPositiveFloatingNumber_whenDividedByNegativeZero_thenReturnNegativeInfinity() {
|
||||
assertEquals(Float.NEGATIVE_INFINITY, 12f / -0f);
|
||||
assertEquals(Double.NEGATIVE_INFINITY, 12f / -0f);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenDividingFloatingNumberZeroByZero_thenReturnNaN() {
|
||||
assertEquals(Float.NaN, 0f / 0);
|
||||
assertEquals(Double.NaN, 0d / 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenABitRepresentationWithAllExponentBitsZeroesAndAllFractionBitsZeroes_whenTransformingItToFloat_thenReturnPositiveZero() {
|
||||
assertEquals(0f, Float.intBitsToFloat(0b00000000000000000000000000000000));
|
||||
assertEquals(-0f, Float.intBitsToFloat(0b10000000000000000000000000000000));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenABitRepresentationWithAllExponentBitsOnesAndAllFractionBitsZeroes_whenTransformingItToFloat_thenReturnInfinity() {
|
||||
assertEquals(Float.POSITIVE_INFINITY, Float.intBitsToFloat(0b01111111100000000000000000000000));
|
||||
assertEquals(Float.NEGATIVE_INFINITY, Float.intBitsToFloat(0b11111111100000000000000000000000));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenABitRepresentationWithAllExponentBitsOnesAndNotAllFractionBitsZeroes_whenTransformingItToFloat_thenReturnNan() {
|
||||
assertEquals(Float.NaN, Float.intBitsToFloat(0b11111111100000010000000000000000));
|
||||
assertEquals(Float.NaN, Float.intBitsToFloat(0b11111111100000011000000000100000));
|
||||
assertEquals(Float.NaN, Float.intBitsToFloat(0b11111111100000011100000000000000));
|
||||
assertEquals(Float.NaN, Float.intBitsToFloat(0b11111111100000011110000000000000));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.doubletolong;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DoubleToLongUnitTest {
|
||||
|
||||
final static double VALUE = 9999.999;
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenLongValueCalled_thenLongValueReturned() {
|
||||
Assert.assertEquals(9999L, Double.valueOf(VALUE).longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathRoundUsed_thenRoundUp() {
|
||||
Assert.assertEquals(10000L, Math.round(VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathRoundUsed_thenRoundDown() {
|
||||
Assert.assertEquals(9999L, Math.round(9999.444));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathRoundUsed_thenSameValueReturned() {
|
||||
Assert.assertEquals(9999L, Math.round(9999.0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathCeilUsed_thenLongValueReturned() {
|
||||
Assert.assertEquals(10000L, Math.ceil(VALUE), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathCeilUsed_thenSameValueReturned() {
|
||||
Assert.assertEquals(9999L, Math.ceil(9999.0), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathCeilUsed_thenDifferentThanRound() {
|
||||
Assert.assertEquals(10000L, Math.ceil(9999.444), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathFloorUsed_thenLongValueReturned() {
|
||||
Assert.assertEquals(9999L, Math.floor(VALUE), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathFloorUsed_thenSameValueReturned() {
|
||||
Assert.assertEquals(9999L, Math.floor(9999.0), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenMathFloorUsed_thenDifferentThanCeil() {
|
||||
Assert.assertEquals(9999L, Math.floor(9999.444), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValue_whenTypeCasted_thenLongValueReturned() {
|
||||
Assert.assertEquals(9999L, (long) VALUE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.fibonacci;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FibonacciSeriesUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTermToCalculate_thenReturnThatTermUsingRecursion() {
|
||||
int term = 10;
|
||||
int expectedValue = 55;
|
||||
assertEquals(FibonacciSeriesUtils.nthFibonacciTermRecursiveMethod(term), expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTermToCalculate_thenReturnThatTermUsingIteration() {
|
||||
int term = 10;
|
||||
int expectedValue = 55;
|
||||
assertEquals(FibonacciSeriesUtils.nthFibonacciTermIterativeMethod(term), expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTermToCalculate_thenReturnThatTermUsingBinetsFormula() {
|
||||
int term = 10;
|
||||
int expectedValue = 55;
|
||||
assertEquals(FibonacciSeriesUtils.nthFibonacciTermUsingBinetsFormula(term), expectedValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.formatNumber;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static com.baeldung.formatNumber.FormatNumber.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class FormatNumberUnitTest {
|
||||
private static final double D = 4.2352989244d;
|
||||
private static final double F = 8.6994540927d;
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumber_whenFormatNumberWithBigDecimal_thenGetExpectedResult() {
|
||||
assertThat(withBigDecimal(D, 2)).isEqualTo(4.24);
|
||||
assertThat(withBigDecimal(D, 3)).isEqualTo(4.235);
|
||||
assertThat(withBigDecimal(F, 2)).isEqualTo(8.7);
|
||||
assertThat(withBigDecimal(F, 3)).isEqualTo(8.699);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumber_whenFormatNumberWithDecimalFormat_thenGetExpectedResult() {
|
||||
assertThat(withDecimalFormatLocal(D)).isEqualTo(4.235);
|
||||
assertThat(withDecimalFormatLocal(F)).isEqualTo(8.699);
|
||||
|
||||
assertThat(withDecimalFormatPattern(D, 2)).isEqualTo(4.24);
|
||||
assertThat(withDecimalFormatPattern(D, 3)).isEqualTo(4.235);
|
||||
assertThat(withDecimalFormatPattern(F, 2)).isEqualTo(8.7);
|
||||
assertThat(withDecimalFormatPattern(F, 3)).isEqualTo(8.699);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumber_whenFormatNumberWithStringFormat_thenGetExpectedResult() {
|
||||
assertThat(withStringFormat(D, 2)).isEqualTo("4.24");
|
||||
assertThat(withStringFormat(D, 3)).isEqualTo("4.235");
|
||||
assertThat(withStringFormat(F, 2)).isEqualTo("8.70");
|
||||
assertThat(withStringFormat(F, 3)).isEqualTo("8.699");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumber_whenFormatNumberWithMathRound_thenGetExpectedResult() {
|
||||
assertThat(withMathRound(D, 2)).isEqualTo(4.24);
|
||||
assertThat(withMathRound(D, 3)).isEqualTo(4.235);
|
||||
assertThat(withMathRound(F, 2)).isEqualTo(8.7);
|
||||
assertThat(withMathRound(F, 3)).isEqualTo(8.699);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerNumber_whenFormatNumberByPaddingOutZeros_thenGetExpectedResult() {
|
||||
int value = 1;
|
||||
assertThat(byPaddingZeros(value, 3)).isEqualTo("001");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerNumber_whenFormatNumberWithTwoDecimalPlaces_thenGetExpectedResult() {
|
||||
int value = 12;
|
||||
assertThat(withTwoDecimalPlaces(value)).isEqualTo(12.00);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerNumber_whenFormatNumberWithLargeIntegers_thenGetExpectedResult() {
|
||||
int value = 123456789;
|
||||
assertThat(withLargeIntegers(value)).isEqualTo("123,456,789");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDecimalNumber_whenFormatNumberForPercentages_thenGetExpectedResult() {
|
||||
double value = 25f / 100f;
|
||||
assertThat(forPercentages(value, new Locale("en", "US"))).isEqualTo("25%");
|
||||
assertThat(forPercentages(value, new Locale("pl", "PL"))).isEqualTo("25%");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCurrency_whenFormatNumberCurrencyWithChosenLocalisation_thenGetExpectedResult() {
|
||||
double value = 23_500;
|
||||
assertThat(currencyWithChosenLocalisation(value, new Locale("en", "US"))).isEqualTo("$23,500.00");
|
||||
assertThat(currencyWithChosenLocalisation(value, new Locale("zh", "CN"))).isEqualTo("¥23,500.00");
|
||||
assertThat(currencyWithChosenLocalisation(value, new Locale("pl", "PL"))).isEqualTo("23 500 zł");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.integerToBinary;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class IntegerToBinaryUnitTest {
|
||||
@Test
|
||||
public void givenAnInteger_whenConvertToBinary_thenGetBinaryString() {
|
||||
int n = 7;
|
||||
String binaryString = IntegerToBinary.convertIntegerToBinary(n);
|
||||
assertEquals("111", binaryString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnInteger_whenToBinaryStringCalled_thenGetBinaryString() {
|
||||
int n = 7;
|
||||
String binaryString = Integer.toBinaryString(n);
|
||||
assertEquals("111", binaryString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnInteger_whenToStringCalled_thenGetBinaryString() {
|
||||
int n = 7;
|
||||
String binaryString = Integer.toString(n, 2);
|
||||
assertEquals("111", binaryString);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.numbersinrange;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumbersInARangeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTheRange1To10_andUsingForLoop_thenExpectCorrectResult() {
|
||||
NumbersInARange numbersInARange = new NumbersInARange();
|
||||
List<Integer> numbers = numbersInARange.getNumbersInRange(1, 10);
|
||||
|
||||
assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,9), numbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheRange1To10_andUsingIntStreamRange_thenExpectCorrectResult() {
|
||||
NumbersInARange numbersInARange = new NumbersInARange();
|
||||
List<Integer> numbers = numbersInARange.getNumbersUsingIntStreamRange(1, 10);
|
||||
|
||||
assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,9), numbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheRange1To10_andUsingIntStreamRangeClosed_thenExpectCorrectResult() {
|
||||
NumbersInARange numbersInARange = new NumbersInARange();
|
||||
List<Integer> numbers = numbersInARange.getNumbersUsingIntStreamRangeClosed(1, 10);
|
||||
|
||||
assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,9,10), numbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheRange1To10_andUsingIntStreamIterate_thenExpectCorrectResult() {
|
||||
NumbersInARange numbersInARange = new NumbersInARange();
|
||||
List<Integer> numbers = numbersInARange.getNumbersUsingIntStreamIterate(1, 10);
|
||||
|
||||
assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,9,10), numbers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.numbersinrange;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RandomNumbersInARangeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTheRange1To10_andUsingMathRandom_thenExpectCorrectResult() {
|
||||
RandomNumbersInARange randomNumbersInARange = new RandomNumbersInARange();
|
||||
int number = randomNumbersInARange.getRandomNumber(1, 10);
|
||||
|
||||
assertTrue(number >= 1);
|
||||
assertTrue(number < 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheRange1To10_andUsingRandomInts_thenExpectCorrectResult() {
|
||||
RandomNumbersInARange randomNumbersInARange = new RandomNumbersInARange();
|
||||
int number = randomNumbersInARange.getRandomNumberUsingInts(1, 10);
|
||||
|
||||
assertTrue(number >= 1);
|
||||
assertTrue(number < 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheRange1To10_andUsingRandomNextInt_thenExpectCorrectResult() {
|
||||
RandomNumbersInARange randomNumbersInARange = new RandomNumbersInARange();
|
||||
int number = randomNumbersInARange.getRandomNumberUsingNextInt(1, 10);
|
||||
|
||||
assertTrue(number >= 1);
|
||||
assertTrue(number < 10);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.baeldung.parsedouble;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
import com.google.common.primitives.Doubles;
|
||||
|
||||
import io.vavr.control.Try;
|
||||
|
||||
public class StringToDoubleParserUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNullValue_whenParseStringToDouble_thenDefaultNaNValueIsReturned() {
|
||||
assertThat(parseStringToDouble(null)).isNaN();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringValue_whenParseStringToDouble_thenDefaultNaNValueIsReturned() {
|
||||
assertThat(parseStringToDouble("")).isNaN();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringValue_whenParseStringToDouble_thenDoubleValueIsReturned() {
|
||||
assertThat(parseStringToDouble("1")).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringValue_whenParseStringToDoubleWithDefault_thenDoubleValueIsReturned() {
|
||||
assertThat(parseStringToDouble("1", 2.0d)).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringValue_whenParseStringToDoubleWithDefault_thenDefaultValueIsReturned() {
|
||||
assertThat(parseStringToDouble("", 1.0d)).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValue_whenParseStringToDoubleWithDefault_thenDefaultValueIsReturned() {
|
||||
assertThat(parseStringToDouble(null, 1.0d)).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringValue_whenParseStringToOptionalDouble_thenOptionalValueIsReturned() {
|
||||
assertThat(parseStringToOptionalDouble("1")).isEqualTo(Optional.of(1.0d));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValue_whenParseStringToOptionalDouble_thenOptionalValueIsEmpty() {
|
||||
assertThat(parseStringToOptionalDouble(null)).isEqualTo(Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringValue_whenParseStringToOptionalDouble_thenOptionalValueIsEmpty() {
|
||||
assertThat(parseStringToOptionalDouble("")).isEqualTo(Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringValue_whenParseStringToOptionalDouble_thenDefaulOptionalValueIsReturned() {
|
||||
assertThat(parseStringToOptionalDouble("").orElse(1.0d)).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValue_whenParseStringToOptionalDouble_thenDefaulOptionalValueIsReturned() {
|
||||
assertThat(parseStringToOptionalDouble(null).orElse(1.0d)).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringValue_whenTryStringToDouble_thenDoubleValueIsReturned() {
|
||||
assertThat(tryStringToDouble("1", 2.0d)).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValue_whenTryStringToDoubleWithDefault_thenDoubleValueIsReturned() {
|
||||
assertThat(tryStringToDouble(null, 2.0d)).isEqualTo(2.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringValue_whenTryStringToDoubleWithDefault_thenDoubleValueIsReturned() {
|
||||
assertThat(tryStringToDouble("", 2.0d)).isEqualTo(2.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStringValues_whenTryParseFirstNonNull_thenDoubleValueIsReturned() {
|
||||
assertThat(Doubles.tryParse(MoreObjects.firstNonNull("1.0", "2.0"))).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullStringValue_whenTryParseFirstNonNull_thenSecondDoubleValueIsReturned() {
|
||||
assertThat(Doubles.tryParse(MoreObjects.firstNonNull(null, "2.0"))).isEqualTo(2.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringValue_whenTryParseFirstNonNull_thenNullIsReturned() {
|
||||
assertThat(Doubles.tryParse(MoreObjects.firstNonNull("", "2.0"))).isEqualTo(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringValue_whenToDouble_thenDoubleValueIsReturned() {
|
||||
assertThat(NumberUtils.toDouble("1.0")).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValue_whenToDouble_thenLibraryDefaultDoubleValueIsReturned() {
|
||||
String nullString = null;
|
||||
assertThat(NumberUtils.toDouble(nullString)).isEqualTo(0.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringValue_whenToDouble_thenLibraryDefaultDoubleValueIsReturned() {
|
||||
assertThat(NumberUtils.toDouble("")).isEqualTo(0.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringValue_whenToDoubleWithDefault_thenDoubleValueIsReturned() {
|
||||
assertThat(NumberUtils.toDouble("", 2.0d)).isEqualTo(2.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValue_whenToDoubleWithDefault_thenDoubleValueIsReturned() {
|
||||
String nullString = null;
|
||||
assertThat(NumberUtils.toDouble(nullString, 2.0d)).isEqualTo(2.0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringValue_whenToDoubleWithDefault_thenDoubleValueIsReturned() {
|
||||
assertThat(NumberUtils.toDouble("1.0", 2.0d)).isEqualTo(1.0d);
|
||||
}
|
||||
|
||||
private static Optional<Double> parseStringToOptionalDouble(String value) {
|
||||
return value == null || value.isEmpty() ? Optional.empty() : Optional.of(Double.valueOf(value));
|
||||
}
|
||||
|
||||
private static double parseStringToDouble(String value) {
|
||||
return value == null || value.isEmpty() ? Double.NaN : Double.parseDouble(value);
|
||||
}
|
||||
|
||||
private static double parseStringToDouble(String value, double defaultValue) {
|
||||
return value == null || value.isEmpty() ? defaultValue : Double.parseDouble(value);
|
||||
}
|
||||
|
||||
private static double tryStringToDouble(String value, double defaultValue) {
|
||||
return Try.of(() -> Double.parseDouble(value)).getOrElse(defaultValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package com.baeldung.randomnumbers;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RandomNumbersGeneratorUnitTest {
|
||||
|
||||
private static final int MIN_RANGE = 1;
|
||||
private static final int MAX_RANGE = 10;
|
||||
private static final int MIN_RANGE_NEGATIVE = -10;
|
||||
private static final int ITERATIONS = 50;
|
||||
private static final long STREAM_SIZE = 50;
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithMathRandom_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumer = generator.generateRandomWithMathRandom(MIN_RANGE, MAX_RANGE);
|
||||
assertTrue(isInRange(randomNumer, MIN_RANGE, MAX_RANGE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithNextInt_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithNextInt();
|
||||
assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithNextIntWithinARange_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithNextIntWithinARange(MIN_RANGE, MAX_RANGE);
|
||||
assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomUnlimitedIntStream_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
IntStream stream = generator.generateRandomUnlimitedIntStream();
|
||||
assertNotNull(stream);
|
||||
Integer randomNumber = stream.findFirst()
|
||||
.getAsInt();
|
||||
assertNotNull(randomNumber);
|
||||
assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomLimitedIntStream_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
generator.generateRandomLimitedIntStream(STREAM_SIZE)
|
||||
.forEach(randomNumber -> assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomLimitedIntStreamWithinARange_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
generator.generateRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE)
|
||||
.forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithThreadLocalRandom_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithThreadLocalRandom();
|
||||
assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithThreadLocalRandomInARange_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithThreadLocalRandomInARange(MIN_RANGE, MAX_RANGE);
|
||||
assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithThreadLocalRandomFromZero_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithThreadLocalRandomFromZero(MAX_RANGE);
|
||||
assertTrue(isInRange(randomNumber, 0, MAX_RANGE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithSplittableRandom_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithSplittableRandom(MIN_RANGE_NEGATIVE, MAX_RANGE);
|
||||
assertTrue(isInRange(randomNumber, MIN_RANGE_NEGATIVE, MAX_RANGE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithSplittableRandomLimitedIntStreamWithinARange_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
generator.generateRandomWithSplittableRandomLimitedIntStreamWithinARange(MIN_RANGE, MAX_RANGE, STREAM_SIZE)
|
||||
.forEach(randomNumber -> assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithSecureRandom_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithSecureRandom();
|
||||
assertTrue(isInRange(randomNumber, Integer.MIN_VALUE, Integer.MAX_VALUE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithSecureRandomWithinARange_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithSecureRandomWithinARange(MIN_RANGE, MAX_RANGE);
|
||||
assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithRandomDataGenerator_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithRandomDataGenerator(MIN_RANGE, MAX_RANGE);
|
||||
// RandomDataGenerator top is inclusive
|
||||
assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE + 1));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGenerateRandomWithXoRoShiRo128PlusRandom_returnsSuccessfully() {
|
||||
RandomNumbersGenerator generator = new RandomNumbersGenerator();
|
||||
for (int i = 0; i < ITERATIONS; i++) {
|
||||
int randomNumber = generator.generateRandomWithXoRoShiRo128PlusRandom(MIN_RANGE, MAX_RANGE);
|
||||
assertTrue(isInRange(randomNumber, MIN_RANGE, MAX_RANGE));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isInRange(int number, int min, int max) {
|
||||
return min <= number && number < max;
|
||||
}
|
||||
|
||||
}
|
||||
11
core-java-modules/java-numbers-4/README.md
Normal file
11
core-java-modules/java-numbers-4/README.md
Normal file
@@ -0,0 +1,11 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Probability in Java](https://www.baeldung.com/java-probability)
|
||||
- [Understanding the & 0xff Value in Java](https://www.baeldung.com/java-and-0xff)
|
||||
- [Determine if an Integer’s Square Root Is an Integer in Java](https://www.baeldung.com/java-find-if-square-root-is-integer)
|
||||
- [Guide to Java BigInteger](https://www.baeldung.com/java-biginteger)
|
||||
- [Automorphic Numbers in Java](https://www.baeldung.com/java-automorphic-numbers)
|
||||
- [Convert Byte Size Into a Human-Readable Format in Java](https://www.baeldung.com/java-human-readable-byte-size)
|
||||
- [Convert boolean to int in Java](https://www.baeldung.com/java-boolean-to-int)
|
||||
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
|
||||
- [Reverse a Number in Java](https://www.baeldung.com/java-reverse-number)
|
||||
47
core-java-modules/java-numbers-4/pom.xml
Normal file
47
core-java-modules/java-numbers-4/pom.xml
Normal file
@@ -0,0 +1,47 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>java-numbers-4</artifactId>
|
||||
<name>java-numbers-4</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-numbers-4</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<vavr.version>0.10.2</vavr.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.automorphicnumber;
|
||||
|
||||
public class AutomorphicNumber {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(isAutomorphicUsingLoop(76));
|
||||
System.out.println(isAutomorphicUsingMath(76));
|
||||
}
|
||||
|
||||
public static boolean isAutomorphicUsingMath(int number) {
|
||||
int square = number * number;
|
||||
|
||||
int numberOfDigits = (int) Math.floor(Math.log10(number) + 1);
|
||||
int lastDigits = (int) (square % (Math.pow(10, numberOfDigits)));
|
||||
|
||||
return number == lastDigits;
|
||||
}
|
||||
|
||||
public static boolean isAutomorphicUsingLoop(int number) {
|
||||
int square = number * number;
|
||||
|
||||
while (number > 0) {
|
||||
if (number % 10 != square % 10) {
|
||||
return false;
|
||||
}
|
||||
number /= 10;
|
||||
square /= 10;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.booleantoint;
|
||||
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
|
||||
public class BooleanToInt {
|
||||
public static int booleanPrimitiveToInt(boolean foo) {
|
||||
int bar = 0;
|
||||
if (foo) {
|
||||
bar = 1;
|
||||
}
|
||||
return bar;
|
||||
}
|
||||
|
||||
public static int booleanPrimitiveToIntTernary(boolean foo) {
|
||||
return (foo) ? 1 : 0;
|
||||
}
|
||||
|
||||
public static int booleanObjectToInt(boolean foo) {
|
||||
return Boolean.compare(foo, false);
|
||||
}
|
||||
|
||||
public static int booleanObjectToIntInverse(boolean foo) {
|
||||
return Boolean.compare(foo, true) + 1;
|
||||
}
|
||||
|
||||
public static int booleanObjectMethodToInt(Boolean foo) {
|
||||
return foo.compareTo(false);
|
||||
}
|
||||
|
||||
public static int booleanObjectMethodToIntInverse(Boolean foo) {
|
||||
return foo.compareTo(true) + 1;
|
||||
}
|
||||
|
||||
public static int booleanUtilsToInt(Boolean foo) {
|
||||
return BooleanUtils.toInteger(foo);
|
||||
}
|
||||
|
||||
public static int bitwiseBooleanToInt(Boolean foo) {
|
||||
return (Boolean.hashCode(foo) >> 1) & 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.convertLongToInt;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
public class ConvertLongToInt {
|
||||
|
||||
static Function<Long, Integer> convert = val -> Optional.ofNullable(val)
|
||||
.map(Long::intValue)
|
||||
.orElse(null);
|
||||
|
||||
public static int longToIntCast(long number) {
|
||||
return (int) number;
|
||||
}
|
||||
|
||||
public static int longToIntJavaWithMath(long number) {
|
||||
return Math.toIntExact(number);
|
||||
}
|
||||
|
||||
public static int longToIntJavaWithLambda(long number) {
|
||||
return convert.apply(number);
|
||||
}
|
||||
|
||||
public static int longToIntBoxingValues(long number) {
|
||||
return Long.valueOf(number)
|
||||
.intValue();
|
||||
}
|
||||
|
||||
public static int longToIntGuava(long number) {
|
||||
return Ints.checkedCast(number);
|
||||
}
|
||||
|
||||
public static int longToIntGuavaSaturated(long number) {
|
||||
return Ints.saturatedCast(number);
|
||||
}
|
||||
|
||||
public static int longToIntWithBigDecimal(long number) {
|
||||
return new BigDecimal(number).intValueExact();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.humanreadablebytes;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class FileSizeFormatUtil {
|
||||
private static final long BYTE = 1L;
|
||||
private static final long KB = BYTE << 10;
|
||||
private static final long MB = KB << 10;
|
||||
private static final long GB = MB << 10;
|
||||
private static final long TB = GB << 10;
|
||||
private static final long PB = TB << 10;
|
||||
private static final long EB = PB << 10;
|
||||
private static final DecimalFormat DEC_FORMAT = new DecimalFormat("#.##");
|
||||
|
||||
public static String toHumanReadable(long size) {
|
||||
if (size < 0)
|
||||
throw new IllegalArgumentException("Invalid file size: " + size);
|
||||
if (size >= EB) return formatSize(size, EB, "EB");
|
||||
if (size >= PB) return formatSize(size, PB, "PB");
|
||||
if (size >= TB) return formatSize(size, TB, "TB");
|
||||
if (size >= GB) return formatSize(size, GB, "GB");
|
||||
if (size >= MB) return formatSize(size, MB, "MB");
|
||||
if (size >= KB) return formatSize(size, KB, "KB");
|
||||
return formatSize(size, BYTE, "Bytes");
|
||||
}
|
||||
|
||||
private static String formatSize(long size, long divider, String unitName) {
|
||||
return DEC_FORMAT.format((double) size / divider) + " " + unitName;
|
||||
}
|
||||
|
||||
public static String toHumanReadableWithEnum(long size) {
|
||||
final List<SizeUnit> units = SizeUnit.unitsInDescending();
|
||||
if (size < 0)
|
||||
throw new IllegalArgumentException("Invalid file size: " + size);
|
||||
String result = null;
|
||||
for (SizeUnit unit : units) {
|
||||
if (size >= unit.getUnitBase()) {
|
||||
result = formatSize(size, unit.getUnitBase(), unit.name());
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result == null ? formatSize(size, SizeUnit.Bytes.getUnitBase(), SizeUnit.Bytes.name()) : result;
|
||||
}
|
||||
|
||||
public static String toHumanReadableByNumOfLeadingZeros(long size) {
|
||||
if (size < 0)
|
||||
throw new IllegalArgumentException("Invalid file size: " + size);
|
||||
if (size < 1024) return size + " Bytes";
|
||||
int unitIdx = (63 - Long.numberOfLeadingZeros(size)) / 10;
|
||||
return formatSize(size, 1L << (unitIdx * 10), " KMGTPE".charAt(unitIdx) + "B");
|
||||
}
|
||||
|
||||
enum SizeUnit {
|
||||
Bytes(1L),
|
||||
KB(Bytes.unitBase << 10),
|
||||
MB(KB.unitBase << 10),
|
||||
GB(MB.unitBase << 10),
|
||||
TB(GB.unitBase << 10),
|
||||
PB(TB.unitBase << 10),
|
||||
EB(PB.unitBase << 10);
|
||||
|
||||
private final Long unitBase;
|
||||
|
||||
public static List<SizeUnit> unitsInDescending() {
|
||||
List<SizeUnit> list = Arrays.asList(values());
|
||||
Collections.reverse(list);
|
||||
return list;
|
||||
}
|
||||
|
||||
public Long getUnitBase() {
|
||||
return unitBase;
|
||||
}
|
||||
|
||||
SizeUnit(long unitBase) {
|
||||
this.unitBase = unitBase;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.number_0xff;
|
||||
|
||||
public class Number0xff {
|
||||
|
||||
public static int getRedColor(int rgba) {
|
||||
return rgba >> 24 & 0xff;
|
||||
}
|
||||
|
||||
public static int getGreenColor(int rgba) {
|
||||
return rgba >> 16 & 0xff;
|
||||
}
|
||||
|
||||
public static int getBlueColor(int rgba) {
|
||||
return rgba >> 8 & 0xff;
|
||||
}
|
||||
|
||||
public static int getAlfa(int rgba) {
|
||||
return rgba & 0xff;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.perfectsquare;
|
||||
|
||||
public class PerfectSquareUtil {
|
||||
|
||||
public static boolean isPerfectSquareByUsingSqrt(long n) {
|
||||
if (n <= 0)
|
||||
return false;
|
||||
double perfectSquare = Math.sqrt(n);
|
||||
long tst = (long)(perfectSquare + 0.5);
|
||||
return tst*tst == n;
|
||||
}
|
||||
|
||||
public static boolean isPerfectSquareByUsingBinarySearch(long low, long high, long number) {
|
||||
long check = (low + high) / 2L;
|
||||
if (high < low)
|
||||
return false;
|
||||
if (number == check * check) {
|
||||
return true;
|
||||
} else if (number < check * check) {
|
||||
high = check - 1L;
|
||||
return isPerfectSquareByUsingBinarySearch(low, high, number);
|
||||
} else {
|
||||
low = check + 1L;
|
||||
return isPerfectSquareByUsingBinarySearch(low, high, number);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isPerfectSquareByUsingNewtonMethod(long n) {
|
||||
long x1 = n;
|
||||
long x2 = 1L;
|
||||
while (x1 > x2) {
|
||||
x1 = (x1 + x2) / 2L;
|
||||
x2 = n / x1;
|
||||
}
|
||||
return x1 == x2 && n % x1 == 0L;
|
||||
}
|
||||
|
||||
public static boolean isPerfectSquareWithOptimization(long n) {
|
||||
if (n < 0)
|
||||
return false;
|
||||
switch ((int) (n & 0xF)) {
|
||||
case 0: case 1: case 4: case 9:
|
||||
long tst = (long) Math.sqrt(n);
|
||||
return tst * tst == n;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.probability;
|
||||
|
||||
import org.apache.commons.math3.distribution.NormalDistribution;
|
||||
|
||||
public class MaleHeightGenerator {
|
||||
private static final double MEAN_HEIGHT = 176.02;
|
||||
private static final double STANDARD_DEVIATION = 7.11;
|
||||
private static NormalDistribution distribution = new NormalDistribution(MEAN_HEIGHT, STANDARD_DEVIATION);
|
||||
|
||||
public static double generateNormalHeight() {
|
||||
return distribution.sample();
|
||||
}
|
||||
|
||||
public static double probabilityOfHeightBetween(double heightLowerExclusive, double heightUpperInclusive) {
|
||||
return distribution.probability(heightLowerExclusive, heightUpperInclusive);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.probability;
|
||||
|
||||
import io.vavr.Lazy;
|
||||
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class RandomInvoker {
|
||||
private final Lazy<SplittableRandom> random = Lazy.of(SplittableRandom::new);
|
||||
|
||||
public <T> T withProbability(Supplier<T> positiveCase, Supplier<T> negativeCase, int probability) {
|
||||
SplittableRandom random = this.random.get();
|
||||
if (random.nextInt(1, 101) <= probability) {
|
||||
return positiveCase.get();
|
||||
} else {
|
||||
return negativeCase.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.reversenumber;
|
||||
|
||||
public class ReverseNumber {
|
||||
|
||||
public static int reverseNumberWhileLoop(int number) {
|
||||
int reversedNumber = 0;
|
||||
int numberToReverse = Math.abs(number);
|
||||
|
||||
while (numberToReverse > 0) {
|
||||
int mod = numberToReverse % 10;
|
||||
reversedNumber = reversedNumber * 10 + mod;
|
||||
numberToReverse /= 10;
|
||||
}
|
||||
|
||||
return number < 0 ? reversedNumber * -1 : reversedNumber;
|
||||
}
|
||||
|
||||
public static int reverseNumberForLoop(int number) {
|
||||
int reversedNumber = 0;
|
||||
int numberToReverse = Math.abs(number);
|
||||
|
||||
for (; numberToReverse > 0; numberToReverse /= 10) {
|
||||
int mod = numberToReverse % 10;
|
||||
reversedNumber = reversedNumber * 10 + mod;
|
||||
}
|
||||
|
||||
return number < 0 ? reversedNumber * -1 : reversedNumber;
|
||||
}
|
||||
|
||||
public static int reverseNumberRecWrapper(int number) {
|
||||
int output = reverseNumberRec(Math.abs(number), 0);
|
||||
return number < 0 ? output * -1 : output;
|
||||
}
|
||||
private static int reverseNumberRec(int numberToReverse, int recursiveReversedNumber) {
|
||||
|
||||
if (numberToReverse > 0) {
|
||||
int mod = numberToReverse % 10;
|
||||
recursiveReversedNumber = recursiveReversedNumber * 10 + mod;
|
||||
numberToReverse /= 10;
|
||||
return reverseNumberRec(numberToReverse, recursiveReversedNumber);
|
||||
}
|
||||
|
||||
return recursiveReversedNumber;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.automorphicnumber;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AutomorphicNumberUnitTest {
|
||||
|
||||
@Test
|
||||
void givenANumber_whenPassed_thenShouldDetermineAutomorphicOrNot() {
|
||||
int number1 = 76; // automorphic
|
||||
int number2 = 16; // not automorphic
|
||||
assertTrue(AutomorphicNumber.isAutomorphicUsingLoop(number1));
|
||||
assertFalse(AutomorphicNumber.isAutomorphicUsingLoop(number2));
|
||||
assertTrue(AutomorphicNumber.isAutomorphicUsingMath(number1));
|
||||
assertFalse(AutomorphicNumber.isAutomorphicUsingMath(number2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.biginteger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class BigIntegerUnitTest {
|
||||
|
||||
@Test
|
||||
void givenPositiveAndNegativeAndZeroBigInteger_whenGetSigNumValue_shouldReturnOneAndMinusOneAndZero() {
|
||||
assertEquals(1, BigInteger.TEN.signum());
|
||||
assertEquals(-1, BigInteger.TEN.negate().signum());
|
||||
assertEquals(0, BigInteger.ZERO.signum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenByteArrays_whenCreateBigInteger_shouldTranslateToTwosComplementBinary() {
|
||||
assertEquals(new BigInteger("1"), new BigInteger(new byte[]{0b1}));
|
||||
assertEquals(new BigInteger("2"), new BigInteger(new byte[]{0b10}));
|
||||
assertEquals(new BigInteger("4"), new BigInteger(new byte[]{0b100}));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSingleByte_whenCreateBigIntegerAndDifferentSigNum_thenOppositeValues() {
|
||||
byte[] bytes = { (byte) -128 }; // 0b1000_0000
|
||||
|
||||
BigInteger positive = new BigInteger(1, bytes);
|
||||
BigInteger negative = new BigInteger(-1, bytes);
|
||||
|
||||
assertEquals(new BigInteger("128"), positive);
|
||||
assertEquals("10000000", positive.toString(2));
|
||||
|
||||
assertEquals(new BigInteger("-128"), negative);
|
||||
assertEquals("-10000000", negative.toString(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenZeroBigInteger_whenCheckMagnitude_thenIsEmpty() {
|
||||
assertEquals(0, BigInteger.ZERO.bitCount());
|
||||
assertEquals(BigInteger.ZERO, new BigInteger(0, new byte[]{}));
|
||||
}
|
||||
|
||||
@Test
|
||||
void given63rdBitSet_whenCreateBigInteger_thenIsLargerThanLongByOne() {
|
||||
// first
|
||||
BigInteger bi1 = BigInteger.ZERO.setBit(63);
|
||||
String str1 = bi1.toString(2);
|
||||
|
||||
// second
|
||||
byte[] bytes = ByteBuffer.allocate(Long.BYTES).putLong(Long.MIN_VALUE).array();
|
||||
BigInteger bi2 = new BigInteger(1, bytes);
|
||||
String str2 = bi2.toString(2);
|
||||
|
||||
largerThanLongAssertionSet(bi1, str1);
|
||||
|
||||
assertEquals(bi1, bi2);
|
||||
|
||||
largerThanLongAssertionSet(bi2, str2);
|
||||
|
||||
}
|
||||
|
||||
private static void largerThanLongAssertionSet(BigInteger bi, String str)
|
||||
{
|
||||
assertEquals(64, bi.bitLength());
|
||||
assertEquals(1, bi.signum());
|
||||
assertEquals("9223372036854775808", bi.toString());
|
||||
assertEquals(BigInteger.ONE, bi.subtract(BigInteger.valueOf(Long.MAX_VALUE)));
|
||||
|
||||
assertEquals(64, str.length());
|
||||
assertTrue(str.matches("^10{63}$")); // 1000 0000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.booleantoint;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class BooleanToIntUnitTest {
|
||||
@Test
|
||||
void givenBooleanPrimitiveValue_ThenReturnInt() {
|
||||
assertEquals(1, BooleanToInt.booleanPrimitiveToInt(true));
|
||||
assertEquals(0, BooleanToInt.booleanPrimitiveToInt(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanPrimitiveValue_ThenReturnIntTernary() {
|
||||
assertEquals(1, BooleanToInt.booleanPrimitiveToIntTernary(true));
|
||||
assertEquals(0, BooleanToInt.booleanPrimitiveToIntTernary(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanObject_ThenReturnInt() {
|
||||
assertEquals(0, BooleanToInt.booleanObjectToInt(false));
|
||||
assertEquals(1, BooleanToInt.booleanObjectToInt(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanObject_ThenReturnIntInverse() {
|
||||
assertEquals(0, BooleanToInt.booleanObjectToIntInverse(false));
|
||||
assertEquals(1, BooleanToInt.booleanObjectToIntInverse(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanObject_ThenReturnIntUsingClassMethod() {
|
||||
assertEquals(0, BooleanToInt.booleanObjectMethodToInt(false));
|
||||
assertEquals(1, BooleanToInt.booleanObjectMethodToInt(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBooleanObject_ThenReturnIntUsingClassMethodInverse() {
|
||||
assertEquals(0, BooleanToInt.booleanObjectMethodToIntInverse(false));
|
||||
assertEquals(1, BooleanToInt.booleanObjectMethodToIntInverse(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBoolean_ThenReturnIntUsingBooleanUtils() {
|
||||
assertEquals(0, BooleanToInt.booleanUtilsToInt(false));
|
||||
assertEquals(1, BooleanToInt.booleanUtilsToInt(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBoolean_ThenReturnIntUsingBitwiseOperators() {
|
||||
assertEquals(0, BooleanToInt.bitwiseBooleanToInt(false));
|
||||
assertEquals(1, BooleanToInt.bitwiseBooleanToInt(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.convertLongToInt;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ConvertLongToIntUnitTest {
|
||||
|
||||
@Test
|
||||
void longToInt() {
|
||||
long number = 186762L;
|
||||
int expected = 186762;
|
||||
|
||||
assertEquals(expected, ConvertLongToInt.longToIntCast(number));
|
||||
assertEquals(expected, ConvertLongToInt.longToIntJavaWithMath(number));
|
||||
assertEquals(expected, ConvertLongToInt.longToIntJavaWithLambda(number));
|
||||
assertEquals(expected, ConvertLongToInt.longToIntBoxingValues(number));
|
||||
assertEquals(expected, ConvertLongToInt.longToIntGuava(number));
|
||||
assertEquals(expected, ConvertLongToInt.longToIntGuavaSaturated(number));
|
||||
assertEquals(expected, ConvertLongToInt.longToIntWithBigDecimal(number));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.humanreadablebytes;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class FileSizeFormatUtilUnitTest {
|
||||
private final static Map<Long, String> DATA_MAP = new HashMap<Long, String>() {{
|
||||
put(0L, "0 Bytes");
|
||||
put(1023L, "1023 Bytes");
|
||||
put(1024L, "1 KB");
|
||||
put(12_345L, "12.06 KB");
|
||||
put(10_123_456L, "9.65 MB");
|
||||
put(10_123_456_798L, "9.43 GB");
|
||||
put(1_777_777_777_777_777_777L, "1.54 EB");
|
||||
}};
|
||||
|
||||
@Test
|
||||
public void givenBytes_whenCalltoHumanReadableMethod_thenGetExpectedResults() {
|
||||
DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadable(in)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBytes_whenCalltoHumanReadableWithEnumMethod_thenGetExpectedResults() {
|
||||
DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableWithEnum(in)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBytes_whenCalltoHumanReadableByLeadingZeros_thenGetExpectedResults() {
|
||||
DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableByNumOfLeadingZeros(in)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBytes_whenCalltoHumanReadableByFileUtils_thenOutputExpectedResults() {
|
||||
DATA_MAP.forEach((in, expected) -> System.out.println(in + " bytes -> " + FileUtils.byteCountToDisplaySize(in)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.number_0xff;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Number0xffUnitTest {
|
||||
|
||||
@Test
|
||||
public void test0xFFAssignedToInteger() {
|
||||
int x = 0xff;
|
||||
int expectedValue = 255;
|
||||
assertEquals(expectedValue, x);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test0xFFAssignedToByte() {
|
||||
byte y = (byte) 0xff;
|
||||
int expectedValue = -1;
|
||||
assertEquals(expectedValue, y);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenColor_whenGetRedColor_thenExtractRedColor() {
|
||||
int rgba = 272214023;
|
||||
int expectedValue = 16;
|
||||
assertEquals(expectedValue, Number0xff.getRedColor(rgba));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenColor_whenGetGreenColor_thenExtractGreenColor() {
|
||||
int rgba = 272214023;
|
||||
int expectedValue = 57;
|
||||
assertEquals(expectedValue, Number0xff.getGreenColor(rgba));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenColor_whenGetBlueColor_thenExtractBlueColor() {
|
||||
int rgba = 272214023;
|
||||
int expectedValue = 168;
|
||||
assertEquals(expectedValue, Number0xff.getBlueColor(rgba));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenColor_whenGetAlfa_thenExtractAlfa() {
|
||||
int rgba = 272214023;
|
||||
int expectedValue = 7;
|
||||
assertEquals(expectedValue, Number0xff.getAlfa(rgba));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.perfectsquare;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PerfectSquareUnitTest {
|
||||
|
||||
@Test
|
||||
public void testIsNumberPerfectSquare() {
|
||||
long n = 18676209273604L; // 18676209273604 = 43621598 * 43621598
|
||||
boolean expectedValue = true;
|
||||
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingSqrt(n));
|
||||
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingBinarySearch(1, Integer.MAX_VALUE, n));
|
||||
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingNewtonMethod(n));
|
||||
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareWithOptimization(n));
|
||||
|
||||
n = 549790047707L; // prime number
|
||||
expectedValue = false;
|
||||
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingSqrt(n));
|
||||
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingBinarySearch(1, Integer.MAX_VALUE, n));
|
||||
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareByUsingNewtonMethod(n));
|
||||
assertEquals(expectedValue, PerfectSquareUtil.isPerfectSquareWithOptimization(n));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.probability;
|
||||
|
||||
import org.assertj.core.data.Offset;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class RandomInvokerUnitTest {
|
||||
@Test
|
||||
public void givenProbability_whenInvoked_invokeWithProbability() {
|
||||
RandomInvoker randomInvoker = new RandomInvoker();
|
||||
|
||||
int numberOfSamples = 1_000_000;
|
||||
int probability = 10;
|
||||
int howManyTimesInvoked = Stream.generate(() -> randomInvoker.withProbability(() -> 1, () -> 0, probability))
|
||||
.limit(numberOfSamples)
|
||||
.mapToInt(e -> e).sum();
|
||||
int monteCarloProbability = (howManyTimesInvoked * 100) / numberOfSamples;
|
||||
|
||||
assertThat(monteCarloProbability).isCloseTo(probability, Offset.offset(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.reversenumber;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ReverseNumberUnitTest {
|
||||
|
||||
private static final int ORIGINAL_NUMBER = 123456789;
|
||||
private static final int REVERSED_NUMBER = 987654321;
|
||||
|
||||
@Test
|
||||
void whenReverseNumberWhileLoop_thenOriginalEqualToReverse() {
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberWhileLoop(ORIGINAL_NUMBER)).isEqualTo(REVERSED_NUMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReverseNumberForLoop_thenOriginalEqualToReverse() {
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberForLoop(ORIGINAL_NUMBER)).isEqualTo(REVERSED_NUMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReverseNumberRec_thenOriginalEqualToReverse() {
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberRecWrapper(ORIGINAL_NUMBER)).isEqualTo(REVERSED_NUMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReverseNegativeNumber_thenNumberShouldReverse() {
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberWhileLoop(ORIGINAL_NUMBER * -1)).isEqualTo(REVERSED_NUMBER * -1);
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberForLoop(ORIGINAL_NUMBER * -1)).isEqualTo(REVERSED_NUMBER * -1);
|
||||
Assertions.assertThat(ReverseNumber.reverseNumberRecWrapper(ORIGINAL_NUMBER * -1)).isEqualTo(REVERSED_NUMBER * -1);
|
||||
}
|
||||
}
|
||||
26
core-java-modules/java-numbers/.gitignore
vendored
Normal file
26
core-java-modules/java-numbers/.gitignore
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
||||
16
core-java-modules/java-numbers/README.md
Normal file
16
core-java-modules/java-numbers/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
## Java Number Cookbooks and Examples
|
||||
|
||||
This module contains articles about numbers in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Number of Digits in an Integer in Java](https://www.baeldung.com/java-number-of-digits-in-int)
|
||||
- [How to Round a Number to N Decimal Places in Java](https://www.baeldung.com/java-round-decimal-number)
|
||||
- [BigDecimal and BigInteger in Java](https://www.baeldung.com/java-bigdecimal-biginteger)
|
||||
- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum in Java](https://www.baeldung.com/java-algorithm-number-pairs-sum)
|
||||
- [Java – Random Long, Float, Integer and Double](https://www.baeldung.com/java-generate-random-long-float-integer-double)
|
||||
- [A Practical Guide to DecimalFormat](https://www.baeldung.com/java-decimalformat)
|
||||
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
|
||||
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
|
||||
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)
|
||||
- [Using Math.sin with Degrees](https://www.baeldung.com/java-math-sin-degrees)
|
||||
- More articles: [[next -->]](/../java-numbers-2)
|
||||
49
core-java-modules/java-numbers/pom.xml
Normal file
49
core-java-modules/java-numbers/pom.xml
Normal file
@@ -0,0 +1,49 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>java-numbers</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>java-numbers</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.decimal4j</groupId>
|
||||
<artifactId>decimal4j</artifactId>
|
||||
<version>${decimal4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-numbers</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
public class BigDecimalDemo {
|
||||
|
||||
/** Calculate total amount to be paid for an item rounded to cents..
|
||||
* @param quantity
|
||||
* @param unitPrice
|
||||
* @param discountRate
|
||||
* @param taxRate
|
||||
* @return
|
||||
*/
|
||||
public static BigDecimal calculateTotalAmount(BigDecimal quantity,
|
||||
BigDecimal unitPrice, BigDecimal discountRate, BigDecimal taxRate) {
|
||||
BigDecimal amount = quantity.multiply(unitPrice);
|
||||
BigDecimal discount = amount.multiply(discountRate);
|
||||
BigDecimal discountedAmount = amount.subtract(discount);
|
||||
BigDecimal tax = discountedAmount.multiply(taxRate);
|
||||
BigDecimal total = discountedAmount.add(tax);
|
||||
|
||||
// round to 2 decimal places using HALF_EVEN
|
||||
BigDecimal roundedTotal = total.setScale(2, RoundingMode.HALF_EVEN);
|
||||
|
||||
return roundedTotal;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,12 @@
|
||||
package com.baeldung.nth.root.calculator;
|
||||
|
||||
public class NthRootCalculator {
|
||||
|
||||
public double calculateWithRound(double base, double n) {
|
||||
return Math.round(calculate(base, n));
|
||||
}
|
||||
|
||||
public double calculate(double base, double n) {
|
||||
return Math.pow(base, 1.0 / n);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.nth.root.main;
|
||||
|
||||
import com.baeldung.nth.root.calculator.NthRootCalculator;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
NthRootCalculator calculator = new NthRootCalculator();
|
||||
Double base = Double.parseDouble(args[0]);
|
||||
Double n = Double.parseDouble(args[1]);
|
||||
Double result = calculator.calculateWithRound(base, n);
|
||||
System.out.println("The " + n + " root of " + base + " equals to " + result + ".");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,36 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.DoubleStream;
|
||||
|
||||
public interface SecureRandomDemo {
|
||||
|
||||
public static void generateSecureRandomValues() {
|
||||
SecureRandom sr = new SecureRandom();
|
||||
|
||||
int randomInt = sr.nextInt();
|
||||
long randomLong = sr.nextLong();
|
||||
float randomFloat = sr.nextFloat();
|
||||
double randomDouble = sr.nextDouble();
|
||||
boolean randomBoolean = sr.nextBoolean();
|
||||
|
||||
IntStream randomIntStream = sr.ints();
|
||||
LongStream randomLongStream = sr.longs();
|
||||
DoubleStream randomDoubleStream = sr.doubles();
|
||||
|
||||
byte[] values = new byte[124];
|
||||
sr.nextBytes(values);
|
||||
}
|
||||
|
||||
public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException {
|
||||
if (algorithm == null || algorithm.isEmpty()) {
|
||||
return new SecureRandom();
|
||||
}
|
||||
|
||||
return SecureRandom.getInstance(algorithm);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
|
||||
public class DoubleToString {
|
||||
|
||||
public static String truncateByCast(double d) {
|
||||
return String.valueOf((int) d);
|
||||
}
|
||||
|
||||
public static String roundWithStringFormat(double d) {
|
||||
return String.format("%.0f", d);
|
||||
}
|
||||
|
||||
public static String truncateWithNumberFormat(double d) {
|
||||
NumberFormat nf = NumberFormat.getInstance();
|
||||
nf.setMaximumFractionDigits(0);
|
||||
nf.setRoundingMode(RoundingMode.FLOOR);
|
||||
return nf.format(d);
|
||||
}
|
||||
|
||||
public static String roundWithNumberFormat(double d) {
|
||||
NumberFormat nf = NumberFormat.getInstance();
|
||||
nf.setMaximumFractionDigits(0);
|
||||
return nf.format(d);
|
||||
}
|
||||
|
||||
public static String truncateWithDecimalFormat(double d) {
|
||||
DecimalFormat df = new DecimalFormat("#,###");
|
||||
df.setRoundingMode(RoundingMode.FLOOR);
|
||||
return df.format(d);
|
||||
}
|
||||
|
||||
public static String roundWithDecimalFormat(double d) {
|
||||
DecimalFormat df = new DecimalFormat("#,###");
|
||||
return df.format(d);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.baeldung.decimalformat;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DecimalFormatExamplesUnitTest {
|
||||
|
||||
double d = 1234567.89;
|
||||
|
||||
@Test
|
||||
public void givenSimpleDecimal_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("#########.###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1234567.89");
|
||||
|
||||
assertThat(new DecimalFormat("000000000.000", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("001234567.890");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSmallerDecimalPattern_WhenFormatting_ThenRounding() {
|
||||
|
||||
assertThat(new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234567.9");
|
||||
|
||||
assertThat(new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234568");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGroupingSeparator_WhenFormatting_ThenGroupedOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#,###.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,567.9");
|
||||
|
||||
assertThat(new DecimalFormat("#,###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,568");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMixedPattern_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("The # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("The 1234568 number");
|
||||
|
||||
assertThat(new DecimalFormat("The '#' # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("The # 1234568 number");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocales_WhenFormatting_ThenCorrectOutput() {
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1,234,567.89");
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ITALIAN)).format(d))
|
||||
.isEqualTo("1.234.567,89");
|
||||
|
||||
assertThat(new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(new Locale("it", "IT"))).format(d))
|
||||
.isEqualTo("1.234.567,89");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenE_WhenFormatting_ThenScientificNotation() {
|
||||
|
||||
assertThat(new DecimalFormat("00.#######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("12.3456789E5");
|
||||
|
||||
assertThat(new DecimalFormat("000.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("123.456789E4");
|
||||
|
||||
assertThat(new DecimalFormat("##0.######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1.23456789E6");
|
||||
|
||||
assertThat(new DecimalFormat("###.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
|
||||
.isEqualTo("1.23456789E6");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenParsing_ThenCorrectOutput() throws ParseException {
|
||||
|
||||
assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH)).parse("1234567.89"))
|
||||
.isEqualTo(1234567.89);
|
||||
|
||||
assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ITALIAN)).parse("1.234.567,89"))
|
||||
.isEqualTo(1234567.89);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringAndBigDecimalFlag_WhenParsing_ThenCorrectOutput() throws ParseException {
|
||||
|
||||
NumberFormat nf = new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH));
|
||||
((DecimalFormat) nf).setParseBigDecimal(true);
|
||||
assertThat(nf.parse("1234567.89")).isEqualTo(BigDecimal.valueOf(1234567.89));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.math.MathContext;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Random;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BigDecimalDemoUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenBigDecimalCreated_thenValueMatches() {
|
||||
BigDecimal bdFromString = new BigDecimal("0.1");
|
||||
BigDecimal bdFromCharArray = new BigDecimal(
|
||||
new char[] { '3', '.', '1', '6', '1', '5' });
|
||||
BigDecimal bdlFromInt = new BigDecimal(42);
|
||||
BigDecimal bdFromLong = new BigDecimal(123412345678901L);
|
||||
BigInteger bigInteger = BigInteger.probablePrime(100, new Random());
|
||||
BigDecimal bdFromBigInteger = new BigDecimal(bigInteger);
|
||||
|
||||
assertEquals("0.1", bdFromString.toString());
|
||||
assertEquals("3.1615", bdFromCharArray.toString());
|
||||
assertEquals("42", bdlFromInt.toString());
|
||||
assertEquals("123412345678901", bdFromLong.toString());
|
||||
assertEquals(bigInteger.toString(), bdFromBigInteger.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBigDecimalCreatedFromDouble_thenValueMayNotMatch() {
|
||||
BigDecimal bdFromDouble = new BigDecimal(0.1d);
|
||||
assertNotEquals("0.1", bdFromDouble.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBigDecimalCreatedUsingValueOf_thenValueMatches() {
|
||||
BigDecimal bdFromLong1 = BigDecimal.valueOf(123412345678901L);
|
||||
BigDecimal bdFromLong2 = BigDecimal.valueOf(123412345678901L, 2);
|
||||
BigDecimal bdFromDouble = BigDecimal.valueOf(0.1d);
|
||||
|
||||
assertEquals("123412345678901", bdFromLong1.toString());
|
||||
assertEquals("1234123456789.01", bdFromLong2.toString());
|
||||
assertEquals("0.1", bdFromDouble.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEqualsCalled_thenSizeAndScaleMatched() {
|
||||
BigDecimal bd1 = new BigDecimal("1.0");
|
||||
BigDecimal bd2 = new BigDecimal("1.00");
|
||||
|
||||
assertFalse(bd1.equals(bd2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingBigDecimals_thenExpectedResult() {
|
||||
BigDecimal bd1 = new BigDecimal("1.0");
|
||||
BigDecimal bd2 = new BigDecimal("1.00");
|
||||
BigDecimal bd3 = new BigDecimal("2.0");
|
||||
|
||||
assertTrue(bd1.compareTo(bd3) < 0);
|
||||
assertTrue(bd3.compareTo(bd1) > 0);
|
||||
assertTrue(bd1.compareTo(bd2) == 0);
|
||||
assertTrue(bd1.compareTo(bd3) <= 0);
|
||||
assertTrue(bd1.compareTo(bd2) >= 0);
|
||||
assertTrue(bd1.compareTo(bd3) != 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPerformingArithmetic_thenExpectedResult() {
|
||||
BigDecimal bd1 = new BigDecimal("4.0");
|
||||
BigDecimal bd2 = new BigDecimal("2.0");
|
||||
|
||||
BigDecimal sum = bd1.add(bd2);
|
||||
BigDecimal difference = bd1.subtract(bd2);
|
||||
BigDecimal quotient = bd1.divide(bd2);
|
||||
BigDecimal product = bd1.multiply(bd2);
|
||||
|
||||
assertTrue(sum.compareTo(new BigDecimal("6.0")) == 0);
|
||||
assertTrue(difference.compareTo(new BigDecimal("2.0")) == 0);
|
||||
assertTrue(quotient.compareTo(new BigDecimal("2.0")) == 0);
|
||||
assertTrue(product.compareTo(new BigDecimal("8.0")) == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingAttributes_thenExpectedResult() {
|
||||
BigDecimal bd = new BigDecimal("-12345.6789");
|
||||
|
||||
assertEquals(9, bd.precision());
|
||||
assertEquals(4, bd.scale());
|
||||
assertEquals(-1, bd.signum());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRoundingDecimal_thenExpectedResult() {
|
||||
BigDecimal bd = new BigDecimal("2.5");
|
||||
// Round to 1 digit using HALF_EVEN
|
||||
BigDecimal rounded = bd
|
||||
.round(new MathContext(1, RoundingMode.HALF_EVEN));
|
||||
|
||||
assertEquals("2", rounded.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPurchaseTxn_whenCalculatingTotalAmount_thenExpectedResult() {
|
||||
BigDecimal quantity = new BigDecimal("4.5");
|
||||
BigDecimal unitPrice = new BigDecimal("2.69");
|
||||
BigDecimal discountRate = new BigDecimal("0.10");
|
||||
BigDecimal taxRate = new BigDecimal("0.0725");
|
||||
|
||||
BigDecimal amountToBePaid = BigDecimalDemo
|
||||
.calculateTotalAmount(quantity, unitPrice, discountRate, taxRate);
|
||||
assertEquals("11.68", amountToBePaid.toString());
|
||||
}
|
||||
}
|
||||
@@ -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,128 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BigIntegerDemoUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenBigIntegerCreatedFromConstructor_thenExpectedResult() {
|
||||
BigInteger biFromString = new BigInteger("1234567890987654321");
|
||||
BigInteger biFromByteArray = new BigInteger(
|
||||
new byte[] { 64, 64, 64, 64, 64, 64 });
|
||||
BigInteger biFromSignMagnitude = new BigInteger(-1,
|
||||
new byte[] { 64, 64, 64, 64, 64, 64 });
|
||||
|
||||
assertEquals("1234567890987654321", biFromString.toString());
|
||||
assertEquals("70644700037184", biFromByteArray.toString());
|
||||
assertEquals("-70644700037184", biFromSignMagnitude.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLongConvertedToBigInteger_thenValueMatches() {
|
||||
BigInteger bi = BigInteger.valueOf(2305843009213693951L);
|
||||
|
||||
assertEquals("2305843009213693951", bi.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whentCompared_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("123456789012345678901234567890");
|
||||
BigInteger j = new BigInteger("123456789012345678901234567891");
|
||||
BigInteger k = new BigInteger("123456789012345678901234567892");
|
||||
|
||||
assertTrue(i.compareTo(i) == 0);
|
||||
assertTrue(j.compareTo(i) > 0);
|
||||
assertTrue(j.compareTo(k) < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenPerformingArithmetic_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("4");
|
||||
BigInteger j = new BigInteger("2");
|
||||
|
||||
BigInteger sum = i.add(j);
|
||||
BigInteger difference = i.subtract(j);
|
||||
BigInteger quotient = i.divide(j);
|
||||
BigInteger product = i.multiply(j);
|
||||
|
||||
assertEquals(new BigInteger("6"), sum);
|
||||
assertEquals(new BigInteger("2"), difference);
|
||||
assertEquals(new BigInteger("2"), quotient);
|
||||
assertEquals(new BigInteger("8"), product);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenPerformingBitOperations_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("17");
|
||||
BigInteger j = new BigInteger("7");
|
||||
|
||||
BigInteger and = i.and(j);
|
||||
BigInteger or = i.or(j);
|
||||
BigInteger not = j.not();
|
||||
BigInteger xor = i.xor(j);
|
||||
BigInteger andNot = i.andNot(j);
|
||||
BigInteger shiftLeft = i.shiftLeft(1);
|
||||
BigInteger shiftRight = i.shiftRight(1);
|
||||
|
||||
assertEquals(new BigInteger("1"), and);
|
||||
assertEquals(new BigInteger("23"), or);
|
||||
assertEquals(new BigInteger("-8"), not);
|
||||
assertEquals(new BigInteger("22"), xor);
|
||||
assertEquals(new BigInteger("16"), andNot);
|
||||
assertEquals(new BigInteger("34"), shiftLeft);
|
||||
assertEquals(new BigInteger("8"), shiftRight);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenPerformingBitManipulations_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("1018");
|
||||
|
||||
int bitCount = i.bitCount();
|
||||
int bitLength = i.bitLength();
|
||||
int getLowestSetBit = i.getLowestSetBit();
|
||||
boolean testBit3 = i.testBit(3);
|
||||
BigInteger setBit12 = i.setBit(12);
|
||||
BigInteger flipBit0 = i.flipBit(0);
|
||||
BigInteger clearBit3 = i.clearBit(3);
|
||||
|
||||
assertEquals(8, bitCount);
|
||||
assertEquals(10, bitLength);
|
||||
assertEquals(1, getLowestSetBit);
|
||||
assertEquals(true, testBit3);
|
||||
assertEquals(new BigInteger("5114"), setBit12);
|
||||
assertEquals(new BigInteger("1019"), flipBit0);
|
||||
assertEquals(new BigInteger("1010"), clearBit3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenModularCalculation_thenExpectedResult() {
|
||||
BigInteger i = new BigInteger("31");
|
||||
BigInteger j = new BigInteger("24");
|
||||
BigInteger k = new BigInteger("16");
|
||||
|
||||
BigInteger gcd = j.gcd(k);
|
||||
BigInteger multiplyAndmod = j.multiply(k)
|
||||
.mod(i);
|
||||
BigInteger modInverse = j.modInverse(i);
|
||||
BigInteger modPow = j.modPow(k, i);
|
||||
|
||||
assertEquals(new BigInteger("8"), gcd);
|
||||
assertEquals(new BigInteger("12"), multiplyAndmod);
|
||||
assertEquals(new BigInteger("22"), modInverse);
|
||||
assertEquals(new BigInteger("7"), modPow);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigIntegers_whenPrimeOperations_thenExpectedResult() {
|
||||
BigInteger i = BigInteger.probablePrime(100, new Random());
|
||||
|
||||
boolean isProbablePrime = i.isProbablePrime(1000);
|
||||
assertEquals(true, isProbablePrime);
|
||||
}
|
||||
}
|
||||
@@ -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,21 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class MathSinUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnAngleInDegrees_whenUsingToRadians_thenResultIsInRadians() {
|
||||
double angleInDegrees = 30;
|
||||
double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5
|
||||
|
||||
double thirtyDegreesInRadians = (double) 1 / 6 * Math.PI;
|
||||
double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5
|
||||
|
||||
assertThat(sinForDegrees, is(sinForRadians));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,22 @@
|
||||
package com.baeldung.nth.root.calculator;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class NthRootCalculatorUnitTest {
|
||||
|
||||
private NthRootCalculator nthRootCalculator = new NthRootCalculator();
|
||||
|
||||
@Test
|
||||
public void whenBaseIs125AndNIs3_thenNthIs5() {
|
||||
double nth = nthRootCalculator.calculateWithRound(125,3);
|
||||
assertEquals(5, nth, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBaseIs625AndNIs4_thenNthIs5() {
|
||||
double nth = nthRootCalculator.calculate(625,4);
|
||||
assertEquals(5, nth, 0.00001);
|
||||
}
|
||||
}
|
||||
@@ -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,156 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import org.apache.commons.math3.random.RandomDataGenerator;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.baeldung.removingdecimals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* This benchmark compares some of the approaches to formatting a floating-point
|
||||
* value into a {@link String} while removing the decimal part.
|
||||
*
|
||||
* To run, simply run the {@link RemovingDecimalsManualTest#runBenchmarks()} test
|
||||
* at the end of this class.
|
||||
*
|
||||
* The benchmark takes about 15 minutes to run. Since it is using {@link Mode#Throughput},
|
||||
* higher numbers mean better performance.
|
||||
*/
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 20)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@State(Scope.Benchmark)
|
||||
public class RemovingDecimalsManualTest {
|
||||
@Param(value = {"345.56", "345345345.56", "345345345345345345.56"}) double doubleValue;
|
||||
|
||||
NumberFormat nf;
|
||||
DecimalFormat df;
|
||||
|
||||
@Setup
|
||||
public void readyFormatters() {
|
||||
nf = NumberFormat.getInstance();
|
||||
nf.setMaximumFractionDigits(0);
|
||||
df = new DecimalFormat("#,###");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenCastToInt_thenValueIsTruncated() {
|
||||
return String.valueOf((int) doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingStringFormat_thenValueIsRounded() {
|
||||
return String.format("%.0f", doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingNumberFormat_thenValueIsRounded() {
|
||||
nf.setRoundingMode(RoundingMode.HALF_UP);
|
||||
return nf.format(doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
|
||||
nf.setRoundingMode(RoundingMode.FLOOR);
|
||||
return nf.format(doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingDecimalFormat_thenValueIsRounded() {
|
||||
df.setRoundingMode(RoundingMode.HALF_UP);
|
||||
return df.format(doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
|
||||
df.setRoundingMode(RoundingMode.FLOOR);
|
||||
return df.format(doubleValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
|
||||
BigDecimal big = new BigDecimal(doubleValue);
|
||||
big = big.setScale(0, RoundingMode.FLOOR);
|
||||
return big.toString();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() {
|
||||
BigDecimal big = new BigDecimal(doubleValue);
|
||||
big = big.setScale(0, RoundingMode.HALF_UP);
|
||||
return big.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runBenchmarks() throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(this.getClass().getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.baeldung.removingdecimals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
/**
|
||||
* Tests that demonstrate some different approaches for formatting a
|
||||
* floating-point value into a {@link String} while removing the decimal part.
|
||||
*/
|
||||
public class RemovingDecimalsUnitTest {
|
||||
private final double doubleValue = 345.56;
|
||||
|
||||
@Test
|
||||
public void whenCastToInt_thenValueIsTruncated() {
|
||||
String truncated = String.valueOf((int) doubleValue);
|
||||
assertEquals("345", truncated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALargeDouble_whenCastToInt_thenValueIsNotTruncated() {
|
||||
double outOfIntRange = 6_000_000_000.56;
|
||||
String truncationAttempt = String.valueOf((int) outOfIntRange);
|
||||
assertNotEquals("6000000000", truncationAttempt);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringFormat_thenValueIsRounded() {
|
||||
String rounded = String.format("%.0f", doubleValue);
|
||||
assertEquals("346", rounded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALargeDouble_whenUsingStringFormat_thenValueIsStillRounded() {
|
||||
double outOfIntRange = 6_000_000_000.56;
|
||||
String rounded = String.format("%.0f", outOfIntRange);
|
||||
assertEquals("6000000001", rounded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingNumberFormat_thenValueIsRounded() {
|
||||
NumberFormat nf = NumberFormat.getInstance();
|
||||
nf.setMaximumFractionDigits(0);
|
||||
nf.setRoundingMode(RoundingMode.HALF_UP);
|
||||
String rounded = nf.format(doubleValue);
|
||||
assertEquals("346", rounded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
|
||||
NumberFormat nf = NumberFormat.getInstance();
|
||||
nf.setMaximumFractionDigits(0);
|
||||
nf.setRoundingMode(RoundingMode.FLOOR);
|
||||
String truncated = nf.format(doubleValue);
|
||||
assertEquals("345", truncated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingDecimalFormat_thenValueIsRounded() {
|
||||
DecimalFormat df = new DecimalFormat("#,###");
|
||||
df.setRoundingMode(RoundingMode.HALF_UP);
|
||||
String rounded = df.format(doubleValue);
|
||||
assertEquals("346", rounded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
|
||||
DecimalFormat df = new DecimalFormat("#,###");
|
||||
df.setRoundingMode(RoundingMode.FLOOR);
|
||||
String truncated = df.format(doubleValue);
|
||||
assertEquals("345", truncated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
|
||||
BigDecimal big = new BigDecimal(doubleValue);
|
||||
big = big.setScale(0, RoundingMode.FLOOR);
|
||||
String truncated = big.toString();
|
||||
assertEquals("345", truncated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() {
|
||||
BigDecimal big = new BigDecimal(doubleValue);
|
||||
big = big.setScale(0, RoundingMode.HALF_UP);
|
||||
String truncated = big.toString();
|
||||
assertEquals("346", truncated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DoubleToStringUnitTest {
|
||||
|
||||
private static final double DOUBLE_VALUE = 3.56;
|
||||
private static final String TRUNCATED_DOUBLE = "3";
|
||||
private static final String ROUNDED_UP_DOUBLE = "4";
|
||||
|
||||
|
||||
@Test
|
||||
public void truncateByCastTest() {
|
||||
assertThat(DoubleToString.truncateByCast(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roundingWithStringFormatTest() {
|
||||
assertThat(DoubleToString.roundWithStringFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void truncateWithNumberFormatTest() {
|
||||
assertThat(DoubleToString.truncateWithNumberFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roundWithNumberFormatTest() {
|
||||
assertThat(DoubleToString.roundWithNumberFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void truncateWithDecimalFormatTest() {
|
||||
assertThat(DoubleToString.truncateWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roundWithDecimalFormatTest() {
|
||||
assertThat(DoubleToString.roundWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -122,7 +122,10 @@
|
||||
<module>java-collections-conversions</module>
|
||||
<module>java-collections-conversions-2</module>
|
||||
<module>java-collections-maps-3</module>
|
||||
<module>pre-jpms</module>
|
||||
<module>java-numbers</module>
|
||||
<module>java-numbers-2</module>
|
||||
<module>java-numbers-3</module>
|
||||
<module>java-numbers-4</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
|
||||
Reference in New Issue
Block a user