Поиск пути по принципу дерева
Код на Руби
def f0(number, log) #
v = 1
n = number + v
# log = "#{log} + #{v}"
log = "#{log} + 1"
return [n, log]
end
def f1(number, log) #
v = 3
n = number * v
# log = "#{log} + #{v}"
log = "(#{log}) * 3"
return [n, log]
end
def countWays(start_num, end_num, op_number, max_steps = 0)
ways = {}
ways.store(start_num.to_s, start_num)
max_steps = max_steps == 0 ? (start_num - end_num).abs : max_steps
count = 0
for steps in 1..max_steps
# puts "steps = #{steps}"
new_ways = {}
ways.each_pair{|log, num|
for k in 0..op_number-1
num1, log1 = f0(num, log) if k == 0
num1, log1 = f1(num, log) if k == 1
if num1 == end_num then
log1 += " = " + end_num.to_s
count += 1
puts log1
elsif num1.between?(start_num, end_num)
new_ways.store(log1, num1)
else
# log1 = log1 + " = " + num1.to_s + " BAD "
# puts log1
end
end
}
# p [steps, ways.size, new_ways.size]
ways = new_ways
end
return count
end
p countWays(5, 49, 2, 49)
Вывод
((5) * 3 + 1) * 3 + 1 = 49
((5) * 3) * 3 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1) * 3 + 1 = 49
(5 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1) * 3 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1 + 1 + 1 + 1 + 1 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1 + 1 + 1 + 1 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1 + 1 + 1 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1 + 1 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5 + 1 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5 + 1) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
(5) * 3 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
5 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 49
15
Ответ 15 вариантов программ
Как это решается аналитически я не знаю, но программно явно быстрее