Zach Smith
Zach Smith

Reputation: 8961

Using random number generator and percentages?

Is there a better way to write this code?

I want 47.37 percent of the time the number should be "odd". 47.37 percent of the time the number should be "even".

random_no = rand*100
if (random_no <= 47.37)
  number = "odd"
elsif (random_no <= 94.74)
  number = "even"
else
  number = "other"
end

Upvotes: 1

Views: 2212

Answers (3)

Kal
Kal

Reputation: 2664

Now that I know it's for a roulette game, I'd go about it differently, using rand(38) to pick a number and then seeing whether it's odd, even or 'other'. To illustrate an OO approach to this:

class Roulette
  def initialize
    spin
  end
  def spin
    @number_showing = rand(38)
  end
  def odd_even?
    if @number_showing == 0 || @number_showing == 37
      return 'other'
    elsif @number_showing.odd?
      return 'odd'
    else
      return 'even'
    end
  end
  def number_showing
    if @number_showing == 37
      return '00'
    else
      return @number_showing.to_s
    end
  end
end

wheel = Roulette.new

10.times do
  wheel.spin
  puts wheel.number_showing
  puts wheel.odd_even?
  puts
end

Upvotes: 2

Kal
Kal

Reputation: 2664

I like Vidaica's answer if you're going for a one liner. But why? I think your code is easier to understand. Alternatively you could save three lines by using a case statement:

number = case rand*100
when 0...47.37 then 'odd'
when 47.37...94.74 then 'even'
else 'other'
end

I also like Cary's comment, about using integers for performance. You could combine that with any of the above solutions.

Upvotes: 2

vidang
vidang

Reputation: 1771

This may be a solution:

{'odd'=> 47.37, 'even'=> 94.74, 'other'=> 100}
.find{|key, value| rand* 100 <= value}.first

Upvotes: 3

Related Questions