From dfb50ed2dcfa74b60188645ff4bf2a0b2e4754ca Mon Sep 17 00:00:00 2001 From: Manuel Bustillo Date: Mon, 9 Dec 2024 18:14:21 +0100 Subject: [PATCH] Avoid stack too deep erros due to excessive recursion --- app/services/vns/engine.rb | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/app/services/vns/engine.rb b/app/services/vns/engine.rb index f4041c6..ee50d45 100644 --- a/app/services/vns/engine.rb +++ b/app/services/vns/engine.rb @@ -29,7 +29,7 @@ module VNS @best_score = @target_function.call(@best_solution) self.class.sequence(@perturbations).each do |perturbation| - optimize(perturbation.new(@best_solution)) + optimize(perturbation) end @best_solution @@ -37,15 +37,22 @@ module VNS private - def optimize(perturbation) - perturbation.each do |alternative_solution| - score = @target_function.call(alternative_solution) - next if score >= @best_score + def optimize(perturbation_klass) + loop do + optimized = false - @best_solution = alternative_solution.deep_dup - @best_score = score + perturbation_klass.new(@best_solution).each do |alternative_solution| + score = @target_function.call(alternative_solution) + next if score >= @best_score - return optimize(perturbation.class.new(@best_solution)) + @best_solution = alternative_solution.deep_dup + @best_score = score + optimized = true + + break + end + + return unless optimized end end end -- 2.47.1