How to generate 3 no-digit repeated random integers, each with distinct digits in JavaScript

1 Answer

0 votes
// ------------------------------------------------------------
// Function: generate_number
// Purpose: Create one 3-digit integer with distinct digits,
//          drawn from a shared pool of available digits.
//          The first digit is never zero, so the result
//          is always a true 3-digit integer.
// ------------------------------------------------------------
function generate_number(available_digits, length = 3) {

    // Choose the first digit from the pool, excluding '0'
    const non_zero_digits = available_digits.filter(d => d !== '0');
    const first_digit = non_zero_digits[Math.floor(Math.random() * non_zero_digits.length)];

    // Remove first digit from pool
    available_digits.splice(available_digits.indexOf(first_digit), 1);

    // Choose the remaining digits from the updated pool
    const remaining = [];
    for (let i = 1; i < length; i++) {
        const d = available_digits[Math.floor(Math.random() * available_digits.length)];
        remaining.push(d);

        // Remove chosen digit
        available_digits.splice(available_digits.indexOf(d), 1);
    }

    // Build the number as a string, then convert to int
    const digits_str = first_digit + remaining.join("");
    return parseInt(digits_str, 10);
}


// ------------------------------------------------------------
// Function: generate_three_distinct_digit_numbers
// Purpose: Produce three integers, each with distinct digits,
//          and no digit repeated across all three numbers.
//          All numbers are guaranteed to be 3 digits long.
// ------------------------------------------------------------
function generate_three_distinct_digit_numbers() {

    // Start with all digits 0–9 as strings
    const digits = [];
    for (let i = 0; i < 10; i++) {
        digits.push(String(i));
    }

    // Generate three numbers, each 3 digits long
    const n1 = generate_number(digits);
    const n2 = generate_number(digits);
    const n3 = generate_number(digits);

    return [n1, n2, n3];
}


// ------------------------------------------------------------
// Main execution
// ------------------------------------------------------------
for (let i = 0; i < 5; i++) {
    const result = generate_three_distinct_digit_numbers();
    console.log(`(${result[0]}, ${result[1]}, ${result[2]})`);
}



/*
run:

(297, 514, 860)
(852, 176, 390)
(173, 596, 204)
(179, 524, 380)
(493, 806, 721)

*/

 



answered 13 hours ago by avibootz

Related questions

...