r/programming • • May 08 '15

Five programming problems every Software Engineer should be able to solve in less than 1 hour

https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
2.5k Upvotes

2.1k comments sorted by

View all comments

2

u/MikeVegan May 08 '15

Who doesn't like fun puzzles? 5th is unfair compared to all the others, here is my solution in python

def one_hundred():
   def __one_hundred__(curr_expression, numbers, action):
      expression_new = [x for x in curr_expression]
      numbers_new = [x for x in numbers]
      number = numbers_new.pop(0)
      if action == 0: #join with last
         last = expression_new.pop()
         expression_new.append(int(str(last) + str(number)))
      if action == 1: #simple addition
         expression_new.append(number)
      if action == 2: #simple subtraction
         expression_new.append(-1 * number)
      if len(numbers_new) == 0 and sum(expression_new) == 100:
         print expression_new
      if (len(numbers_new) > 0):
         __one_hundred__(expression_new, numbers_new, 0)
         __one_hundred__(expression_new, numbers_new, 1)
         __one_hundred__(expression_new, numbers_new, 2)
   __one_hundred__([], range(1, 10), 1)
   __one_hundred__([], range(1, 10), 2)

1

u/vegiimite May 08 '15
    private static List<string> Calc100()
    {
        List<string> formulas = new List<string>();

        Calc100_internal(1, new List<int> { 2, 3, 4, 5, 6, 7, 8, 9 }, 99, "1", formulas);

        return formulas;
    }

    private static void Calc100_internal(int val, IEnumerable<int> values, int total, string formula, List<string> formulas)
    {            
        if (values.Count() == 0 )
        {
            if (total == 0)
                formulas.Add(formula);
        }
        else
        {
            int newVal = values.ElementAt(0);

            // + next number, reduce running total
            Calc100_internal(newVal, values.Skip(1), total - newVal, formula + " + " + newVal.ToString(), formulas);
            // - next number, increase running total
            Calc100_internal(-newVal, values.Skip(1), total + newVal, formula + " - " + newVal.ToString(), formulas);
            // append next number, recalc running total
            Calc100_internal(val * 10 + newVal, values.Skip(1), total + val - (val * 10 + newVal), formula + newVal.ToString(), formulas);
        }
    }

1

u/MikeVegan May 08 '15

I think you're missing some values:

Calc100_internal(1, new List<int> { 2, 3, 4, 5, 6, 7, 8, 9 }, 99, "1", formulas);

you're missing some where equation starts with -1

and in

Calc100_internal(val * 10 + newVal, values.Skip(1), total + val - (val * 10 + newVal), formula + newVal.ToString(), formulas);

if val is negative you should get some messed up results and also miss some valid ones due to this. That's why I'm doing conversions to strings in my code.