## philipp@fehre.co.uk

BAN USER
Comments (2)

Reputation 0

Page:

1

Comment hidden because of low score. Click to expand.

Comment hidden because of low score. Click to expand.

0

of 0 vote

As we have 3 options for every number and "+" and "-" at the beginning will even each other out we are left with the options that start with "nothing", this means the solution will not always be 0, but actually some positive number. My quick brute force approach looks like this:

```
def sum_all sum_strings
sum_strings.inject(0) { |acc, s| acc += eval(s) }
end
def all_sums_rec number_array, sum_strings
return sum_all(sum_strings) if number_array.empty?
next_element = number_array.shift
next_sum_strings = sum_strings.flat_map do |s|
no = "#{s}#{next_element}"
plus = "#{s}+#{next_element}"
minus = "#{s}-#{next_element}"
[no, plus, minus]
end
all_sums_rec number_array, next_sum_strings
end
def all_sums number
all_sums_rec number.to_s.split(""), [""]
end
```

This follows basically exactly the problem statement, expanding the number into its elements and building the equations from this expanded number, in the end using "eval" to evaluate what the equation results to and sum them all up.

- philipp@fehre.co.uk April 08, 2017Page:

1

**CareerCup**is the world's biggest and best source for software engineering interview preparation. See all our resources.

A recursive solution can be pretty straight forward for this. Basically use the normal recursive way to compute all the permutations of a string but skip the ones where the char would be at its original position.

- philipp@fehre.co.uk April 14, 2017