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

Show parent comments

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.