From 909eba4575c9685df5cb4f3d98d3d5aa159f3a62e43c2c2d563475ba50fc5434 Mon Sep 17 00:00:00 2001 From: Minimons Date: Wed, 26 Nov 2025 15:25:16 +0100 Subject: [PATCH] NoIssue: Add RandomValueGeneratorInt --- build.gradle.kts | 2 +- .../impl/ref/RandomValueGeneratorIntImpl.java | 54 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/r35157/libs/random/impl/ref/RandomValueGeneratorIntImpl.java diff --git a/build.gradle.kts b/build.gradle.kts index 10b5c7b..a3cea79 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -30,7 +30,7 @@ repositories { dependencies { implementation("org.jetbrains:annotations:26.0.1") implementation("log4j:log4j:1.2.17") - implementation("com.r35157.libs:random-api:0.0.0") + implementation("com.r35157.libs:random-api:0.1-dev") } java { diff --git a/src/main/java/com/r35157/libs/random/impl/ref/RandomValueGeneratorIntImpl.java b/src/main/java/com/r35157/libs/random/impl/ref/RandomValueGeneratorIntImpl.java new file mode 100644 index 0000000..def82c8 --- /dev/null +++ b/src/main/java/com/r35157/libs/random/impl/ref/RandomValueGeneratorIntImpl.java @@ -0,0 +1,54 @@ +package com.r35157.libs.random.impl.ref; + +import com.r35157.libs.random.RandomValueGeneratorInt; + +import java.util.concurrent.ThreadLocalRandom; + +import static java.lang.Integer.MAX_VALUE; +import static java.lang.Integer.MIN_VALUE; + +public class RandomValueGeneratorIntImpl implements RandomValueGeneratorInt { + @Override + public int getSomeInt() { + // Default: use the full int range + return getSomeInt(MIN_VALUE, MAX_VALUE); + } + + @Override + public int getSomeInt(int minInclusive, int maxInclusive) { + if (minInclusive > maxInclusive) { + String errorMessage = String.format("'minInclusive' (%d) must be less than or equal to 'maxInclusive' (%d)", + minInclusive, maxInclusive); + throw new IllegalArgumentException(errorMessage); + } + + if (minInclusive == maxInclusive) { + // Edge case: only one possible value + return minInclusive; + } + + // Fast path: full int range – ThreadLocalRandom.nextInt() already covers it + if (minInclusive == MIN_VALUE && maxInclusive == MAX_VALUE) { + return ThreadLocalRandom.current().nextInt(); + } + + // Use long to avoid overflow when calculating range size + long bound = ((long) maxInclusive - (long) minInclusive) + 1L; + + if (bound <= Integer.MAX_VALUE) { + // Normal case: the range fits in an int + // nextInt(bound) gives a uniform value in [0, bound], + // then shift it into the target range by adding minInclusive + return minInclusive + ThreadLocalRandom.current().nextInt((int) bound); + } else { + // Rare case: the range is larger than Integer.MAX_VALUE + // (e.g. almost the full int space). Use rejection sampling: + // draw values until one falls within the desired interval. + int r; + do { + r = ThreadLocalRandom.current().nextInt(); + } while (r < minInclusive || r > maxInclusive); + return r; + } + } +} \ No newline at end of file