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

22

u/howdoidoit123 May 08 '15

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 always 100. For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100.

I can't figure this one out

1

u/TynanSylvester May 09 '15

I managed to solve it in 52 minutes, brute force. I guess I can't call myself a software engineer :( Not that I ever did anyway :D Warning, some awful code below.

class Program
{
	enum Op
	{
		Plus,
		Minus,
		Combine
	}

	static void Main(string[] args)
	{
		List<Op> curSolution = new List<Op>();
		for( int i=0; i<8; i++ )
		{
			curSolution.Add( Op.Plus );
		}

		int solIndex = 0;
		while( true )
		{
			if( Total( curSolution ) == 100 )
				Console.WriteLine( SolString( curSolution ) );
			//Console.ReadKey();

			if( !curSolution.Any(o=>o != Op.Combine ) )
				break;

                             //Move to next solution
			curSolution.Clear();
			int siLocal = solIndex;
			for( int i=0; i<8; i++ )
			{
				curSolution.Add( (Op)(siLocal%3) );
				siLocal /= 3;
			}

			solIndex++;

		}	

		Console.ReadKey();

	}

	static int Total( List<Op> ops )
	{
		int total = 0;

		for( int i=-1; i<ops.Count; )
		{
			if( i < 0 || ops[i] == Op.Plus )
			{
				total += SubTotalFrom(ops, ref i);
				i++;
			}
			else if( ops[i] == Op.Minus )
			{
				total -= SubTotalFrom(ops, ref i);
				i++;
			}
			else
			{
				throw new InvalidOperationException();
			}
		}

		return total;
	}

	static int SubTotalFrom( List<Op> ops, ref int i )
	{
		int subTotal = i+2;

		while( i<7 && ops[i+1] == Op.Combine )
		{
			subTotal *= 10; 

			i++;
			subTotal += i+2;
		}

		return subTotal;
	}

	static string SolString( List<Op> ops )
	{
		string s = "";
		for( int i=1; i<=9; i++ )
		{
			s += i.ToString();

			if( i == 9 )
				break;

			switch( ops[i-1] )
			{
				case Op.Plus: s += "+"; break;
				case Op.Minus: s += "-"; break;
				case Op.Combine: s += ""; break;
			}
		}

		s += " = " + Total(ops);

		return s;
	}
}