1

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?

3
  • 1
    Do you require 45 random numbers in the range 0 to 5 ? Commented Nov 11, 2016 at 6:27
  • nope. I wanted to create 45 random numbers. But if a number reached more than 5, stop using that number in the random numbers. Commented Nov 11, 2016 at 6:35
  • 1
    @EjayTan your explanation seems a bit complicated. You want a shuffled array containing each number from 1 to 9 exactly 5 times. Commented Nov 11, 2016 at 8:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

To could also use Array#* to avoid flatten. i.e.: ((1..9).to_a * 5).shuffle
3.times should probably be 45.times. Wouldn't it be cleaner to just remove elements until the array is empty instead of having the magic number 45 in there? Something like while (n = numbers.pop); puts n; end. Also note that pop removes the last element which might be counterintuitive.
@Stefan I totally agree. I meant the 3.times part only as an example how to use pop that is easily pasteable into the console. I guess the OP doesn't just want to write a program that prints the values to the console. Therefore IMO it depends on the usage of this randomly order array, how he might want to consume its content. But using while is certainly better than a magic number. You are right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.