patternrubyMinor
Lottery number generator
Viewed 0 times
numberlotterygenerator
Problem
def getRandomNumbers(count, min, max)
array = []
while array.length < count
tmp = rand(max) + min
if array.include?(tmp)
next
else
array.push(tmp)
end
end
return array
end
def prettyPrint(someArray)
string = ""
someArray.each do |item|
string += item.to_s + "\t"
end
puts string
end
array = getRandomNumbers(6, 1, 49)
prettyPrint(array)I'm just learning Ruby and wrote this little two functions just to play around and get a feel for Ruby syntax etc.
I wanted a function that generates a given amount of random numbers within certain limits. In this example for 6 lottery numbers, therefore each number should only occur once. The second method is pretty self explanatory.
The code runs and does what he is supposed to do. However, what are nice tweaks and tricks to make this code nicer and utilizing the abilities of Ruby?
Solution
A min-max pair would be slightly better represented using a
The loop can be written a bit more succinctly.
The pretty-printing function should also be written in one line instead.
Range. In fact, starting with Ruby 1.9, rand can accept a range.The loop can be written a bit more succinctly.
The pretty-printing function should also be written in one line instead.
lower_case is a more conventional naming convention. An explicit return is not necessary, as the code returns the last value anyway.def get_random_numbers(range, count=1)
array = []
while array.length < count
n = rand(range)
array.push(n) unless array.include?(n)
end
array
end
def pretty_print(array)
puts array.join("\t")
end
pretty_print(get_random_numbers(1..49, 6)Code Snippets
def get_random_numbers(range, count=1)
array = []
while array.length < count
n = rand(range)
array.push(n) unless array.include?(n)
end
array
end
def pretty_print(array)
puts array.join("\t")
end
pretty_print(get_random_numbers(1..49, 6)Context
StackExchange Code Review Q#82139, answer score: 6
Revisions (0)
No revisions yet.