发出返回正确值

时间:2014-11-06 00:54:35

标签: ruby scope return

def sum_two(arry, sum)
  p check_sums(sum, arry[0], arry[1..arry.length - 1])
end

def check_sums(target, first_num, remaining_nums)
  result = []
  return result if remaining_nums == []

  remaining_nums.each do |n|
    if first_num + n == target
      result << [first_num, n]
    end
  end
  check_sums(target, remaining_nums[0], remaining_nums[1..remaining_nums.length - 1])
end

my_arry = [2,4,6,1,3,5,7]
my_sum = 6

sum_two(my_arry, my_sum)

以上是我对练习面试问题的解决方案。但是,输出始终为空数组([])。我的问题似乎很简陋,因为我只需要返回最终结果数组,所以我必须遗漏一些明显的东西。基本上,我无法弄清楚为什么它打印一个空阵列,因为我觉得逻辑是合理的。

更新:

下面是我的解决方案的更新版本,其中我将方法包装在一个类中,并使结果成为一个实例变量,以便我可以在整个递归调用中保持其状态。感谢@BenE提到我每次递归调用时都重置了值。这真的为我清理了!这是我的新解决方案:

class SumTwo
  @result = []

  def self.sum_two(arry, sum)
    p SumTwo.check_sums(sum, arry[0], arry[1..arry.length - 1])
  end

  def self.check_sums(target, first_num, remaining_nums)
    return @result if remaining_nums == []

    remaining_nums.each do |n|
      if first_num + n == target
        @result << [first_num, n]
      end
    end
    check_sums(target, remaining_nums[0], remaining_nums[1..remaining_nums.length - 1])
    @result
  end
end
my_arry = [2,4,6,1,3,5,7]
my_sum = 6

SumTwo.sum_two(my_arry, my_sum)

2 个答案:

答案 0 :(得分:2)

问题是你没有返回你循环的result数组,只有当remaning_nums为空时才返回它,这是一个有效的代码解决方案:

def sum_two(arry, sum)
  p check_sums(sum, arry[0], arry[1..arry.length - 1],[])
end

def check_sums(target, first_num, remaining_nums,result)
  return result if remaining_nums == []

  remaining_nums.each do |n|
    if first_num + n == target
      result << [first_num, n]
    end
  end
  check_sums(target, remaining_nums[0], remaining_nums[1..remaining_nums.length - 1],result)
  result
end

my_arry = [2,4,6,1,3,5,7]
my_sum = 6

sum_two(my_arry, my_sum)

答案 1 :(得分:0)

如果你想返回数组中所有数字对的总和是给定值,我认为使用Array#combination方法最简单:

def sum_two(arry, sum)
  arry.combination(2).select { |i,j| i+j == sum }
end

sum_two [2,4,6,1,3,5,7], 6
  #=> [[2, 4], [1, 5]]

sum_two [*(1..24)], 12
  #=> [[1, 11], [2, 10], [3, 9], [4, 8], [5, 7]]

sum_two [1,3, 6, 8, 2, 9, 3, 5, 7, 8, 16], 17
  #=> [[1, 16], [8, 9], [9, 8]]

如果您想在上一个示例中删除[8, 9][9, 8],则可以执行此操作:

def sum_two(arry, sum)
  arry.uniq.combination(2).select { |i,j| i+j == sum }
end

sum_two [1,3, 6, 8, 2, 9, 3, 5, 7, 8, 16], 17
  #=> [[1, 16], [8, 9]]