Search code examples
rubyrandomprobability

Ruby - How to generate 1% chance of item in array?


I have 3 classification rarity with probability something like this

class S has 10% probability

class A has 30% probability

class B has 60% probability

So i code like this

pool = ["S", "A", "A", "A", "B", "B", "B", "B", "B", "B"]
11.times do
 puts pool[rand(10) - 1]
end

and the result is quite correct in my guest (cmiiw)

B
A
B
B
S
B
A
S
B
A
B

but i become confuse when i should add more class and change S class probability to 1%

pool now become

class S has 1% probability

class A has 29% probability

class B has 30% probability

class C has 40% probability

i am not sure i should create pool like pool variable before because 1% is 1/10 is not integer.

Kindly need help, thanks!


Solution

  • pool = 100.times.map do
      r = rand
    
      if r <= 0.01
        'S'
      elsif r <= 0.30
        'A'
      elsif r <= 0.6
        'B'
      else
        'D'
      end
    end
    p pool
    p pool.tally
    

    This would output something like

    ["D", "B", "D", ....]
    {"D"=>39, "B"=>28, "A"=>31, "S"=>2}
    

    You could also force rand to return an Integer:

    r = rand(0..100)

    and then check for integers

    if r <= 1

    or use a case statement and check for ranges like in the in the answer linked by Stefan.