fix: handle Null Dereference in NthUglyNumber (#5469)

This commit is contained in:
Piotr Idzik
2024-09-24 20:00:38 +02:00
committed by GitHub
parent 1460eb7bbe
commit 27343e7aa8
2 changed files with 10 additions and 13 deletions

View File

@ -9,7 +9,6 @@
"src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java",
"src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java",
"src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java",
"src/main/java/com/thealgorithms/maths/NthUglyNumber.java",
"src/main/java/com/thealgorithms/maths/SimpsonIntegration.java",
"src/main/java/com/thealgorithms/others/Dijkstra.java",
"src/main/java/com/thealgorithms/sorts/TopologicalSort.java",

View File

@ -2,7 +2,7 @@ package com.thealgorithms.maths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.commons.lang3.tuple.MutablePair;
/**
* @brief class computing the n-th ugly number (when they are sorted)
@ -16,8 +16,7 @@ import java.util.HashMap;
*/
public class NthUglyNumber {
private ArrayList<Long> uglyNumbers = new ArrayList<>(Arrays.asList(1L));
private final int[] baseNumbers;
private HashMap<Integer, Integer> positions = new HashMap<>();
private ArrayList<MutablePair<Integer, Integer>> positions = new ArrayList<>();
/**
* @brief initialized the object allowing to compute ugly numbers with given base
@ -29,9 +28,8 @@ public class NthUglyNumber {
throw new IllegalArgumentException("baseNumbers must be non-empty.");
}
this.baseNumbers = baseNumbers;
for (final var baseNumber : baseNumbers) {
this.positions.put(baseNumber, 0);
this.positions.add(MutablePair.of(baseNumber, 0));
}
}
@ -59,21 +57,21 @@ public class NthUglyNumber {
private void updatePositions() {
final var lastUglyNumber = uglyNumbers.get(uglyNumbers.size() - 1);
for (final var baseNumber : baseNumbers) {
if (computeCandidate(baseNumber) == lastUglyNumber) {
positions.put(baseNumber, positions.get(baseNumber) + 1);
for (var entry : positions) {
if (computeCandidate(entry) == lastUglyNumber) {
entry.setValue(entry.getValue() + 1);
}
}
}
private long computeCandidate(final int candidateBase) {
return candidateBase * uglyNumbers.get(positions.get(candidateBase));
private long computeCandidate(final MutablePair<Integer, Integer> entry) {
return entry.getKey() * uglyNumbers.get(entry.getValue());
}
private long computeMinimalCandidate() {
long res = Long.MAX_VALUE;
for (final var baseNumber : baseNumbers) {
res = Math.min(res, computeCandidate(baseNumber));
for (final var entry : positions) {
res = Math.min(res, computeCandidate(entry));
}
return res;
}