Skip to content

Instantly share code, notes, and snippets.

@dt1973
Last active October 5, 2015 14:39
Show Gist options
  • Save dt1973/0f48bc9e8abdc1d462c2 to your computer and use it in GitHub Desktop.
Save dt1973/0f48bc9e8abdc1d462c2 to your computer and use it in GitHub Desktop.

Run external scripts randomly according to probabilities ranging from 0.1 to 1.0

NOW WORKING: It shouldn't consecutively repeat the same item

Old script, working fine, but consecutively repeats the same item

airplane.rb

% ruby airplane.rb
0.5
0.5
0.5
0.4
0.5
0.5

New script whose goal is to prevent repeating, NOW WORKING

airplane2.rb

% ruby airplane2.rb
...
# Run external scripts randomly according to probabilities ranging from 0.1 to 1.0
require_relative "method_05.rb"
require_relative "method_04.rb"
require_relative "method_03.rb"
airplanes = {
0.5 => [
method(:five)
],
0.4 => [
method(:four)
],
0.3 => [
method(:three)
]
}
# Independent probabilities, not required to make the sum total of 1.0
probability_bottom = 0.0
airplanes_probabalized = airplanes.each_with_object({}) do |(probability, group), range|
probability_top = probability_bottom + probability
range[(probability_bottom...probability_top)] = group
probability_bottom = probability_top
end
while true
random = Kernel.rand
airplanes_probabalized.each do |range, airplane|
if range.include?(random)
current_airplane = airplane.sample
current_airplane.call
sleep 2
end
end
end
# Run external scripts randomly according to probabilities ranging from 0.1 to 1.0
require_relative "method_05.rb"
require_relative "method_04.rb"
require_relative "method_03.rb"
airplanes = {
0.5 => [
method(:five)
],
0.4 => [
method(:four)
],
0.3 => [
method(:three)
]
}
# Independent probabilities, not required to make the sum total of 1.0
probability_bottom = 0.0
airplanes_probabalized = airplanes.each_with_object({}) do |(probability, group), range|
probability_top = probability_bottom + probability
range[(probability_bottom...probability_top)] = group
probability_bottom = probability_top
end
previous_airplane = nil
while true
random = Kernel.rand
airplanes_probabalized.each do |range, airplane|
if range.include?(random)
current_airplane = airplane.sample
unless previous_airplane == current_airplane
current_airplane.call
previous_airplane = current_airplane
sleep 2
end
end
end
end
def three
puts "0.3"
end
def four
puts "0.4"
end
def five
puts "0.5"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment