Macpon7
Macpon7

Reputation: 9

How do I generate a number in a percentage range?

I am making a text adventure game and have to randomise the stats of my hero's enemies.

Is there a way to generate a random whole number from within a percentage range? Like this: BaseHealth ± 10%, where BaseHealth is a variable.

Upvotes: 0

Views: 951

Answers (4)

sawa
sawa

Reputation: 168091

If BaseHealth is integer,

def take_random base, percent
  d = (base * percent / 100.0).to_i
  base - d + rand(d * 2)
end

take_random(BaseHealth, 10)

or following Stefan's suggestion,

def take_random base, percent
  d = (base * percent / 100.0).to_i
  rand(base - d..base + d)
end

take_random(BaseHealth, 10)

Upvotes: 2

BroiSatse
BroiSatse

Reputation: 44685

def randomize_value(value, percent)
  bottom = (value * (1 - percent / 100.0)).to_i
  up = (value * (1 + percent / 100.0)).to_i
  (bottom..up).to_a.sample
end

health = randomize_value(BaseHealth, 10)

This is assuming that health is to be integer.

Upvotes: 2

MrDuk
MrDuk

Reputation: 18242

This can be accomplished with some basic arithmetic:

TotalHealth = BaseHealth + (BaseHealth * (rand(21)-10)/100)

This will take the BaseHealth and multiply it by a random number 0..20 minus 10, converted to a percent.

Assume BaseHealth = 20:

  • If rand returns 17, you get 7/100 = .07 so TotalHealth = 21.41
  • If rand returns 7, you get -7/100 = -.07 so TotalHealth = 18.6

Upvotes: 0

Marco Prins
Marco Prins

Reputation: 7419

I understand what you mean now

You can do this:

BaseHealth = ( rand(BaseHealth * 0.2) + BaseHealth*0.9 ).to_i

Upvotes: 0

Related Questions