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