mirror of
https://github.com/iib0011/omni-tools.git
synced 2026-11-25 23:24:14 +03:00
Merge pull request #414 from arimu1/fix/404-unique-decimal-domain
fix(random-number): bound unique decimal domain to [min, max] (#404)
This commit is contained in:
3 files changed
+221
-70
No files matched your search
@@ -20,6 +20,21 @@ const initialValues: InitialValuesType = {
|
||||
separator: ', '
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses a numeric field without silently snapping back to a default.
|
||||
* Empty or non-numeric input becomes NaN so that validateInput can
|
||||
* surface a proper, specific error instead of the field just reverting.
|
||||
*/
|
||||
const parseNumericField = (value: string): number => {
|
||||
if (value.trim() === '') {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
const parsed = Number(value);
|
||||
|
||||
return Number.isNaN(parsed) ? NaN : parsed;
|
||||
};
|
||||
|
||||
export default function RandomNumberGenerator({
|
||||
title,
|
||||
longDescription
|
||||
@@ -35,7 +50,8 @@ export default function RandomNumberGenerator({
|
||||
setResult(null);
|
||||
setFormattedResult('');
|
||||
|
||||
// Validate input
|
||||
// Validate input - this is the single source of truth for what
|
||||
// counts as valid, including range/count/domain-size checks.
|
||||
const validationError = validateInput(values);
|
||||
if (validationError) {
|
||||
setError(validationError);
|
||||
@@ -55,7 +71,13 @@ export default function RandomNumberGenerator({
|
||||
setFormattedResult(formatted);
|
||||
} catch (err) {
|
||||
console.error('Random number generation failed:', err);
|
||||
setError(t('randomNumberGenerator.error.generationFailed'));
|
||||
// Prefer the specific error message when we have one (e.g. thrown
|
||||
// from generateRandomNumbers), falling back to a generic message
|
||||
const message =
|
||||
err instanceof Error && err.message
|
||||
? err.message
|
||||
: t('randomNumberGenerator.error.generationFailed');
|
||||
setError(message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -70,7 +92,7 @@ export default function RandomNumberGenerator({
|
||||
<TextFieldWithDesc
|
||||
value={values.minValue.toString()}
|
||||
onOwnChange={(value) =>
|
||||
updateField('minValue', parseInt(value) || 1)
|
||||
updateField('minValue', parseNumericField(value))
|
||||
}
|
||||
description={t(
|
||||
'randomNumberGenerator.options.range.minDescription'
|
||||
@@ -83,7 +105,7 @@ export default function RandomNumberGenerator({
|
||||
<TextFieldWithDesc
|
||||
value={values.maxValue.toString()}
|
||||
onOwnChange={(value) =>
|
||||
updateField('maxValue', parseInt(value) || 100)
|
||||
updateField('maxValue', parseNumericField(value))
|
||||
}
|
||||
description={t(
|
||||
'randomNumberGenerator.options.range.maxDescription'
|
||||
@@ -102,7 +124,9 @@ export default function RandomNumberGenerator({
|
||||
<Box>
|
||||
<TextFieldWithDesc
|
||||
value={values.count.toString()}
|
||||
onOwnChange={(value) => updateField('count', parseInt(value) || 10)}
|
||||
onOwnChange={(value) =>
|
||||
updateField('count', parseNumericField(value))
|
||||
}
|
||||
description={t(
|
||||
'randomNumberGenerator.options.generation.countDescription'
|
||||
)}
|
||||
|
||||
+39
-1
@@ -72,6 +72,44 @@ describe('Random Number Generator Service', () => {
|
||||
expect(uniqueNumbers.size).toBe(3);
|
||||
});
|
||||
|
||||
it('should generate unique decimals within a narrow range without exceeding the max (#404)', () => {
|
||||
const options: InitialValuesType = {
|
||||
minValue: 0,
|
||||
maxValue: 1,
|
||||
count: 3,
|
||||
allowDecimals: true,
|
||||
allowDuplicates: false,
|
||||
sortResults: false,
|
||||
separator: ', '
|
||||
};
|
||||
|
||||
const result = generateRandomNumbers(options);
|
||||
|
||||
expect(result.numbers).toHaveLength(3);
|
||||
expect(new Set(result.numbers).size).toBe(3);
|
||||
result.numbers.forEach((num) => {
|
||||
expect(num).toBeGreaterThanOrEqual(0);
|
||||
expect(num).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('should still reject a unique count larger than the decimal domain (#404)', () => {
|
||||
const options: InitialValuesType = {
|
||||
minValue: 0,
|
||||
maxValue: 1,
|
||||
// hundredths in [0, 1] inclusive give 101 distinct values
|
||||
count: 102,
|
||||
allowDecimals: true,
|
||||
allowDuplicates: false,
|
||||
sortResults: false,
|
||||
separator: ', '
|
||||
};
|
||||
|
||||
expect(() => generateRandomNumbers(options)).toThrow(
|
||||
'Count exceeds the number of unique values available in this range'
|
||||
);
|
||||
});
|
||||
|
||||
it('should sort results when sortResults is true', () => {
|
||||
const options: InitialValuesType = {
|
||||
minValue: 1,
|
||||
@@ -138,7 +176,7 @@ describe('Random Number Generator Service', () => {
|
||||
};
|
||||
|
||||
expect(() => generateRandomNumbers(options)).toThrow(
|
||||
'Cannot generate unique numbers: count exceeds available range'
|
||||
'Count exceeds the number of unique values available in this range'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
import { InitialValuesType, RandomNumberResult } from './types';
|
||||
|
||||
/**
|
||||
* Internal precision used for decimal generation (2 = hundredths).
|
||||
* Change this single constant to support a different precision everywhere.
|
||||
*/
|
||||
const DECIMAL_PRECISION = 2;
|
||||
const DECIMAL_SCALE = 10 ** DECIMAL_PRECISION;
|
||||
|
||||
/** Safety valve for the random-sampling path (rejection sampling). */
|
||||
const MAX_SAMPLING_ATTEMPTS_MULTIPLIER = 50;
|
||||
|
||||
/**
|
||||
* Generate random numbers within a specified range
|
||||
*/
|
||||
export function generateRandomNumbers(
|
||||
options: InitialValuesType
|
||||
): RandomNumberResult {
|
||||
const validationError = validateInput(options);
|
||||
|
||||
if (validationError) {
|
||||
throw new Error(validationError);
|
||||
}
|
||||
|
||||
const {
|
||||
minValue,
|
||||
maxValue,
|
||||
@@ -15,66 +31,32 @@ export function generateRandomNumbers(
|
||||
sortResults
|
||||
} = options;
|
||||
|
||||
if (minValue >= maxValue) {
|
||||
throw new Error('Minimum value must be less than maximum value');
|
||||
}
|
||||
|
||||
if (count <= 0) {
|
||||
throw new Error('Count must be greater than 0');
|
||||
}
|
||||
|
||||
if (!allowDuplicates && count > maxValue - minValue + 1) {
|
||||
throw new Error(
|
||||
'Cannot generate unique numbers: count exceeds available range'
|
||||
);
|
||||
}
|
||||
|
||||
const numbers: number[] = [];
|
||||
|
||||
if (allowDuplicates) {
|
||||
// Generate random numbers with possible duplicates
|
||||
for (let i = 0; i < count; i++) {
|
||||
const randomNumber = generateRandomNumber(
|
||||
minValue,
|
||||
maxValue,
|
||||
allowDecimals
|
||||
);
|
||||
numbers.push(randomNumber);
|
||||
numbers.push(generateRandomNumber(minValue, maxValue, allowDecimals));
|
||||
}
|
||||
} else {
|
||||
// Generate unique random numbers
|
||||
const availableNumbers = new Set<number>();
|
||||
const domainSize = getUniqueDomainSize(minValue, maxValue, allowDecimals);
|
||||
|
||||
// Create a pool of available numbers
|
||||
for (let i = minValue; i <= maxValue; i++) {
|
||||
if (allowDecimals) {
|
||||
// For decimals, we need to generate more granular values
|
||||
for (let j = 0; j < 100; j++) {
|
||||
availableNumbers.add(i + j / 100);
|
||||
}
|
||||
} else {
|
||||
availableNumbers.add(i);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* If we need only a small part of the domain,
|
||||
* avoid creating the whole array.
|
||||
*/
|
||||
if (count < domainSize / 4) {
|
||||
numbers.push(
|
||||
...generateUniqueRandomValues(minValue, maxValue, count, allowDecimals)
|
||||
);
|
||||
} else {
|
||||
const domain = buildUniqueDomain(minValue, maxValue, allowDecimals);
|
||||
|
||||
const availableArray = Array.from(availableNumbers);
|
||||
shuffle(domain);
|
||||
|
||||
// Shuffle the available numbers
|
||||
for (let i = availableArray.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[availableArray[i], availableArray[j]] = [
|
||||
availableArray[j],
|
||||
availableArray[i]
|
||||
];
|
||||
}
|
||||
|
||||
// Take the first 'count' numbers
|
||||
for (let i = 0; i < Math.min(count, availableArray.length); i++) {
|
||||
numbers.push(availableArray[i]);
|
||||
numbers.push(...domain.slice(0, count));
|
||||
}
|
||||
}
|
||||
|
||||
// Sort if requested
|
||||
if (sortResults) {
|
||||
numbers.sort((a, b) => a - b);
|
||||
}
|
||||
@@ -84,13 +66,102 @@ export function generateRandomNumbers(
|
||||
min: minValue,
|
||||
max: maxValue,
|
||||
count,
|
||||
hasDuplicates: !allowDuplicates && hasDuplicatesInArray(numbers),
|
||||
// Only worth checking when duplicates were actually allowed;
|
||||
// otherwise they're guaranteed unique by construction.
|
||||
hasDuplicates: allowDuplicates ? hasDuplicatesInArray(numbers) : false,
|
||||
isSorted: sortResults
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a single random number within the specified range
|
||||
* Calculate the amount of possible unique values
|
||||
* without creating the domain.
|
||||
*/
|
||||
function getUniqueDomainSize(
|
||||
min: number,
|
||||
max: number,
|
||||
allowDecimals: boolean
|
||||
): number {
|
||||
if (allowDecimals) {
|
||||
return (
|
||||
Math.round(max * DECIMAL_SCALE) - Math.round(min * DECIMAL_SCALE) + 1
|
||||
);
|
||||
}
|
||||
|
||||
return Math.floor(max) - Math.ceil(min) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate unique values using random sampling.
|
||||
* Optimized when count is small compared to the domain.
|
||||
* Includes a safety valve in case of unexpectedly high collision rates.
|
||||
*/
|
||||
function generateUniqueRandomValues(
|
||||
min: number,
|
||||
max: number,
|
||||
count: number,
|
||||
allowDecimals: boolean
|
||||
): number[] {
|
||||
const result = new Set<number>();
|
||||
const maxAttempts = Math.max(count * MAX_SAMPLING_ATTEMPTS_MULTIPLIER, 1000);
|
||||
let attempts = 0;
|
||||
|
||||
while (result.size < count) {
|
||||
if (attempts >= maxAttempts) {
|
||||
// Extremely unlikely given the count < domainSize/4 guard upstream,
|
||||
// but this prevents an infinite loop if that invariant is ever broken.
|
||||
throw new Error(
|
||||
'Unable to generate enough unique values within a reasonable number of attempts'
|
||||
);
|
||||
}
|
||||
|
||||
result.add(generateRandomNumber(min, max, allowDecimals));
|
||||
attempts++;
|
||||
}
|
||||
|
||||
return [...result];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build bounded unique domain.
|
||||
* Decimal values use DECIMAL_PRECISION internally.
|
||||
*/
|
||||
function buildUniqueDomain(
|
||||
min: number,
|
||||
max: number,
|
||||
allowDecimals: boolean
|
||||
): number[] {
|
||||
const domain: number[] = [];
|
||||
|
||||
if (allowDecimals) {
|
||||
const start = Math.round(min * DECIMAL_SCALE);
|
||||
const end = Math.round(max * DECIMAL_SCALE);
|
||||
|
||||
for (let value = start; value <= end; value++) {
|
||||
domain.push(value / DECIMAL_SCALE);
|
||||
}
|
||||
} else {
|
||||
for (let value = Math.ceil(min); value <= Math.floor(max); value++) {
|
||||
domain.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
return domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fisher-Yates shuffle
|
||||
*/
|
||||
function shuffle(array: number[]): void {
|
||||
for (let i = array.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
|
||||
[array[i], array[j]] = [array[j], array[i]];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a single random number
|
||||
*/
|
||||
function generateRandomNumber(
|
||||
min: number,
|
||||
@@ -98,24 +169,19 @@ function generateRandomNumber(
|
||||
allowDecimals: boolean
|
||||
): number {
|
||||
if (allowDecimals) {
|
||||
return Math.random() * (max - min) + min;
|
||||
} else {
|
||||
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||||
return Number(
|
||||
(Math.random() * (max - min) + min).toFixed(DECIMAL_PRECISION)
|
||||
);
|
||||
}
|
||||
|
||||
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an array has duplicate values
|
||||
* Check duplicate values
|
||||
*/
|
||||
function hasDuplicatesInArray(arr: number[]): boolean {
|
||||
const seen = new Set<number>();
|
||||
for (const num of arr) {
|
||||
if (seen.has(num)) {
|
||||
return true;
|
||||
}
|
||||
seen.add(num);
|
||||
}
|
||||
return false;
|
||||
return new Set(arr).size !== arr.length;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,16 +193,27 @@ export function formatNumbers(
|
||||
allowDecimals: boolean
|
||||
): string {
|
||||
return numbers
|
||||
.map((num) => (allowDecimals ? num.toFixed(2) : Math.round(num).toString()))
|
||||
.map((num) =>
|
||||
allowDecimals
|
||||
? num.toFixed(DECIMAL_PRECISION)
|
||||
: Math.round(num).toString()
|
||||
)
|
||||
.join(separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate input parameters
|
||||
* Validate input parameters.
|
||||
* This is the single source of truth for input constraints and is
|
||||
* enforced both here (for early/explicit checks) and internally by
|
||||
* generateRandomNumbers (so it's safe to call standalone).
|
||||
*/
|
||||
export function validateInput(options: InitialValuesType): string | null {
|
||||
const { minValue, maxValue, count } = options;
|
||||
|
||||
if (Number.isNaN(minValue) || Number.isNaN(maxValue) || Number.isNaN(count)) {
|
||||
return 'Please enter valid numbers for min, max, and count';
|
||||
}
|
||||
|
||||
if (minValue >= maxValue) {
|
||||
return 'Minimum value must be less than maximum value';
|
||||
}
|
||||
@@ -153,5 +230,17 @@ export function validateInput(options: InitialValuesType): string | null {
|
||||
return 'Range cannot exceed 1,000,000';
|
||||
}
|
||||
|
||||
if (!options.allowDuplicates) {
|
||||
const domainSize = getUniqueDomainSize(
|
||||
minValue,
|
||||
maxValue,
|
||||
options.allowDecimals
|
||||
);
|
||||
|
||||
if (count > domainSize) {
|
||||
return 'Count exceeds the number of unique values available in this range';
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user