tacotuesday
tacotuesday

Reputation: 33

Ruby. Random numbers generator

I'm new to Ruby. I just want to know if there is a way to create random numbers in the following fashion:

1) Generate 45 random numbers.

2) Random number generated can be repeated only up to 5 times

I tried using the following approach.

45.times do |x|
  puts x.rand(1..9)
end 

How can I achieve max occurrence of a number be 5?

Upvotes: 1

Views: 230

Answers (1)

spickermann
spickermann

Reputation: 107077

I would do something like this:

Array.new(5) { (1..9).to_a }.flatten.shuffle

This generates an array in which all number form 1 to 9 exist exactly 5 times and shuffles that array randomly.

Depending on your needs you might use this array as it is or pop the next random number from it:

numbers = Array.new(5) { (1..9).to_a }.flatten.shuffle

3.times do 
  puts numbers.pop
end

Using pop returns a number and removes it from the array. That means after 45 circles the numbers array will be empty.

Upvotes: 2

Related Questions