How to generate N random integers, each with distinct digits and exact length L in JavaScript

1 Answer

0 votes
/**
 * Generate N random integers, each with distinct digits and exact length L.
 * @param {number} N - How many numbers to generate.
 * @param {number} L - Exact length of each number.
 * @returns {number[]} Array of generated integers.
 */
function generateDistinctDigitNumbers(N, L) {
    const results = new Set(); // Use Set to avoid duplicates

    while (results.size < N) {
        // Generate a random number with exactly L digits
        const min = Math.pow(10, L - 1);      // Smallest L‑digit number
        const max = Math.pow(10, L) - 1;      // Largest L‑digit number
        const num = Math.floor(Math.random() * (max - min + 1)) + min;

        // Convert number to string to check digits
        const digits = num.toString();

        // Check if all digits are distinct using a Set
        const digitSet = new Set(digits);

        if (digitSet.size === digits.length) {
            results.add(num); // Add only if digits are unique
        }
    }

    return Array.from(results);
}

// Usage:
console.log(generateDistinctDigitNumbers(10, 6));



/*
run:

[
  312504, 723649,
  102576, 298074,
  253684, 932670,
  523046, 361824,
  194670, 358260
]

*/

 



answered Jul 16 by avibootz

Related questions

...