Reputation: 365
I got the task to create a lottery program which outputs 6 random numbers from 1 to 49 without duplicates. I'm not allowed to use the shuffle-Method of Arrays and as a tip I recieved that I should create an array with 49 entries and "shuffle" the numbers. I thought about this tip but it's not really helping.
This is what I got till now, I hope someone understands my code. I'm still stuck in a more Java way of writing than in ruby.
# Generating the Array
l_num = Array.new(6)
i = 0
while (i == 0)
l_num << [rand(1...49), rand(1...49), rand(1...49), rand(1...49), rand(1...49), rand(1...49)]
if (l_num.uniq.length == l_num.length)
i += 1
end
end
#Output
puts 'Todays lottery numbers are'
l_num.each { |a| print a, " " }
I picked up the uniq-Methode, because I read that it could elimante doubles that way, but I don't think it works in this case. In previous versions of my code I got a Error because I was trying to override the allready created array, I understand why Ruby is giving me an error but I have no clue how to do it in another way.
I hope someone is able to provide me some code-pieces, methods, solutions or tips for this task, thanks in advance.
Upvotes: 1
Views: 2013
Reputation: 4251
min_lottery_number = 1
max_lottery_number = 49
total_size = 6
(min_lottery_number..max_lottery_number).to_a.sample(total_size)
Upvotes: 0
Reputation: 110725
Here's one way to do it you can't use sample
:
a = *1..49
#=> [1, 2, 3,..., 49]
6.times.map { a.delete_at(rand(a.size))+1 }
# => [44, 41, 15, 19, 46, 17]
Upvotes: 2
Reputation: 16110
This is the strategy I would take:
lottery_numbers = []
begin
# add 1 because otherwise it gives you numbers from 0-48
number = rand(49)+1
lottery_numbers.push(number) unless lottery_numbers.include?(number)
end while lottery_numbers.size < 6
puts "lottery numbers:"
puts lottery_numbers.join(" ")
Rubyists tend to initialize arrays with []
as opposed to the verbose Array.new
Upvotes: 4
Reputation: 15129
Charles, I think the easiest would be the following:
Array.new(49) { |x| x + 1 }.sample(6)
However this is what I believe you was prohibited to do? If yes, try a more "manual" solution:
Array.new(49) { |x| x + 1 }.sort { rand() - 0.5 }.take(6)
Otherwise, try implementing one completely "manual" solution. For example:
require 'set'
result = Set.new
loop do
result << 1 + rand(49)
break if result.size == 6
end
puts result.to_a.inspect
Upvotes: 2