Last active
March 15, 2017 04:43
-
-
Save jamesdabbs/13588dcab8a61a11f997a410d7ce6ef9 to your computer and use it in GitHub Desktop.
ant.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'progressbar' | |
class Ant | |
attr_reader :x, :y | |
def initialize | |
@x, @y = 0, 0 | |
end | |
def move | |
case rand(1 .. 5) | |
when 1 | |
@y += 1 if @y < 2 | |
when 2 | |
@x += 1 if @x < 2 | |
when 3 | |
@y -= 1 if @y > -2 | |
when 4 | |
@x -= 1 if @x > -2 | |
end | |
end | |
end | |
NUM_TRIALS = (ARGV.shift || 100_000).to_i | |
NUM_STEPS = (ARGV.shift || 3_600).to_i | |
bar = ProgressBar.create title: 'Simulating', total: NUM_TRIALS | |
# Run the simulation and record ending points | |
results = {} | |
NUM_TRIALS.times do | |
bar.increment | |
ant = Ant.new | |
NUM_STEPS.times do | |
ant.move | |
end | |
results[ [ant.x, ant.y] ] ||= 0 | |
results[ [ant.x, ant.y] ] += 1 | |
end | |
# Tally up number that ended on an edge | |
on_edge = 0 | |
results.each do |(x,y), count| | |
if x == 2 || x == -2 || y == 2 || y == -2 | |
on_edge += count | |
end | |
end | |
def percent n | |
((100.0 * n) / NUM_TRIALS).to_s + '%' | |
end | |
puts "#{percent on_edge} on edge" | |
ranked = results.sort_by { |_, count| count } | |
sq, count = ranked.first | |
puts "#{sq}: #{count} (#{percent count})" | |
sq, count = ranked.last | |
puts "#{sq}: #{count} (#{percent count})" | |
count = results[ [0,0] ] | |
puts "[0, 0]: #{count} (#{percent count})" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment