Add part 2 solution (check out the previous commit for part 1.)

This commit is contained in:
Danila Fedorin 2018-12-15 03:06:32 -08:00
parent b7518c96a1
commit 6ff1d97c91

View File

@ -213,9 +213,10 @@ end
def step(map, units) def step(map, units)
sort_reading_order(units) sort_reading_order(units)
index = 0 index = 0
elf_death_count = 0
while index < units.size while index < units.size
return true if (units.count &.[:type].==(:elf)) == 0 return nil if (units.count &.[:type].==(:elf)) == 0
return true if (units.count &.[:type].==(:goblin)) == 0 return nil if (units.count &.[:type].==(:goblin)) == 0
unit = units[index] unit = units[index]
unit = moved_unit(map, units, unit) unit = moved_unit(map, units, unit)
@ -224,6 +225,7 @@ def step(map, units)
if attacked_u if attacked_u
attacked_index, attacked_unit = attacked_u attacked_index, attacked_unit = attacked_u
if attacked_unit[:hp] <= 0 if attacked_unit[:hp] <= 0
elf_death_count += 1 if attacked_unit[:type] == :elf
units.delete_at attacked_index units.delete_at attacked_index
index -= 1 if index >= attacked_index index -= 1 if index >= attacked_index
else else
@ -233,7 +235,7 @@ def step(map, units)
index += 1 index += 1
end end
return false return elf_death_count
end end
def check_win(units) def check_win(units)
@ -252,16 +254,29 @@ def winning_score(units, type)
units.select(&.[:type].==(type)).sum &.[:hp] units.select(&.[:type].==(type)).sum &.[:hp]
end end
simulating_units = units.dup power = 3
steps = 0 loop do
# draw(map, simulating_units) simulating_units = units.dup.map do |unit|
until won = check_win(simulating_units) next unit unless unit[:type] == :elf
steps += 1 unless step(map, simulating_units) { x: unit[:x], y: unit[:y], hp: unit[:hp], type: :elf, power: power }
end
steps = 0
died = false
# draw(map, simulating_units) # draw(map, simulating_units)
sort_reading_order(simulating_units) until won = check_win(simulating_units) || died
# simulating_units.each do |unit| result = step(map, simulating_units)
# puts "health (#{unit[:type]}): #{unit[:hp]}" if result
# end steps += 1
# puts "-- (end of roun #{steps})" died = result > 0
end
# draw(map, simulating_units)
sort_reading_order(simulating_units)
# simulating_units.each do |unit|
# puts "health (#{unit[:type]}): #{unit[:hp]}"
# end
# puts "-- (end of roun #{steps})"
end
puts "(power: #{power}) #{steps} * #{winning_score(simulating_units, won)} = #{steps * winning_score(simulating_units, won)}"
break if !died && won != :goblin
power += 1
end end
puts "#{steps} * #{winning_score(simulating_units, won)} = #{steps * winning_score(simulating_units, won)}"