Skip to content

Instantly share code, notes, and snippets.

@petertseng
Created November 14, 2017 04:39
Show Gist options
  • Select an option

  • Save petertseng/5162e400f5d2e7a5832b207fef98a5f7 to your computer and use it in GitHub Desktop.

Select an option

Save petertseng/5162e400f5d2e7a5832b207fef98a5f7 to your computer and use it in GitHub Desktop.
add up to 100
def ops(nums, result, sign = 1)
case nums.size
when 0, 1
result == (nums[0] || 0) * sign ? [[nums[0]].compact] : []
else
n1, n2 = nums.first(2)
plus = ops(nums.drop(1), result - n1 * sign, 1).map { |r| [n1, :+] + r }
minus = ops(nums.drop(1), result - n1 * sign, -1).map { |r| [n1, :-] + r }
concat = ops([n1 * 10 + n2] + nums.drop(2), result, sign)
plus + minus + concat
end
end
ops([1, 2, 3, 4, 5, 6, 7, 8, 9], 100).each { |n| puts n.join }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment