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

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.
# ------------------------------------------------------------
def generate_number(available_digits, length = 3)
  # Choose the first digit from the pool, excluding '0'
  non_zero_digits = available_digits.select { |d| d != '0' }
  first_digit = non_zero_digits.sample
  available_digits.delete(first_digit)

  # Choose the remaining digits from the updated pool
  remaining = []
  (length - 1).times do
    d = available_digits.sample
    remaining << d
    available_digits.delete(d)
  end

  # Build the number as a string, then convert to int
  digits_str = first_digit + remaining.join
  digits_str.to_i
end


# ------------------------------------------------------------
# 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.
# ------------------------------------------------------------
def generate_three_distinct_digit_numbers
  # Start with all digits 0–9 as strings
  digits = (0..9).map(&:to_s)

  # Generate three numbers, each 3 digits long
  n1 = generate_number(digits)
  n2 = generate_number(digits)
  n3 = generate_number(digits)

  [n1, n2, n3]
end


# ------------------------------------------------------------
# Main execution
# ------------------------------------------------------------
5.times do
  result = generate_three_distinct_digit_numbers
  puts "(#{result[0]}, #{result[1]}, #{result[2]})"
end



=begin
run:

(736, 408, 951)
(426, 598, 170)
(123, 987, 654)
(901, 285, 463)
(916, 734, 208)

=end

 



answered 11 hours ago by avibootz

Related questions

...