def p_bit(position) position.to_s(2).split('').map(&:to_i).inject(:+) end n = gets.to_i reached = [1] deep = 0 rd = [[1]] loop do array = [] rd[deep].each do |position| b = p_bit(position) [position + b, position - b].each do |a| next if a < 0 || a > n unless reached.include?(a) array << a reached << a end end end deep += 1 if array.include?(n) puts deep + 1 break end if array.empty? puts -1 break end rd << array end