Skip to content

Instantly share code, notes, and snippets.

@cheerfulstoic
Created April 29, 2019 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheerfulstoic/2f6e04fdcdac1242a3a69e3e7209cac7 to your computer and use it in GitHub Desktop.
Save cheerfulstoic/2f6e04fdcdac1242a3a69e3e7209cac7 to your computer and use it in GitHub Desktop.
def die_roll
rand(6) + 1
end
def attack(attacking_count, defending_count)
attacking_dice = [attacking_count, 3].min
defending_dice = [defending_count, 2].min
attacking_rolls = attacking_dice.times.map { die_roll }.sort.reverse
defending_rolls = defending_dice.times.map { die_roll }.sort.reverse
attackers_lost = 0
defenders_lost = 0
if attacking_rolls[0] > defending_rolls[0]
defenders_lost += 1
else
attackers_lost += 1
end
if attacking_rolls[1] && defending_rolls[1]
if attacking_rolls[1] > defending_rolls[1]
defenders_lost += 1
else
attackers_lost += 1
end
end
[attackers_lost, defenders_lost]
end
def battle(attacking_count, defending_count)
while attacking_count > 0 && defending_count > 0
attackers_lost, defenders_lost = attack(attacking_count, defending_count)
attacking_count -= attackers_lost
defending_count -= defenders_lost
end
success = defending_count.zero?
[attacking_count, defending_count, success]
end
attacking_count = ARGV[0].to_i
defending_count = ARGV[1].to_i
simulations = 100_000
success_count = 0
attackers_left_array = []
simulations.times do
result = battle(attacking_count, defending_count)
success_count += 1 if result.last
attackers_left_array << result.first
puts result.join(',')
end
puts "Change of success: #{100 * success_count.fdiv(simulations)}%"
puts "Average number of attackers left: #{attackers_left_array.sum.fdiv(simulations)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment