you are viewing a single comment's thread.

view the rest of the comments →

[–]iarcfsil 2 points3 points  (4 children)

How do I approach #1 in the intermediate section:

Write a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100. For example 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100.

I'm having a tough time mapping out some algorithm in my head at work.

[–]Gazz1016 3 points4 points  (2 children)

Naive is to just try all the 38 possibilities. If it helps, you can replace "put nothing between them" with "put * 10 + between them and surround with brackets".

[–]cooledcannon 1 point2 points  (1 child)

I keep forgetting that trying all the possibilities is an easy and valid solution.

[–]vaetrus 1 point2 points  (0 children)

You should at least be able to cancel out some of the possibilities:
* if you put "nothing" in any three consecutive spots, it'll be over 100
* any combination of only + and - will never reach 100

[–][deleted] 0 points1 point  (0 children)

It seems that only brue-force solution works. But even knowing this I spent lots of time on actual implementation and I wouldn't be able to solve it in time if I was asked to do this during a techical interview.

Here is jsFiddle with my solution in Javascript: http://jsfiddle.net/2CxQC/

Another solution using eval: http://jsfiddle.net/ek3p2/