I recently had an interview in which I was asked to write a method for calculating a response from a string with prefix formatting.
The response to the interview was that I had to use Linq
I am a little confused where I had to use linq and wondered if anyone could help me.
Problem
The signature method should be:
int Calculate(string expression)
I did not need to check the input, but some examples were given
- "+ 3 4" should give 7
- "- 2 10" must indicate -8
- "* 10 -20" should indicate -200
- "/ 6 2" should give 3
My solution is from memory
So, I created unit tests and developed the code at TDD Manor
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod_Add()
{
var calculator = new Calculator();
var result = calculator.Calculate("+ 4 2");
var expected = 6;
Assert.AreEqual(expected, result);
}
[Test]
public void TestMethod_Sub()
{
var calculator = new Calculator();
var result = calculator.Calculate("- 2 10");
var expected = -8;
Assert.AreEqual(expected, result);
}
[Test]
public void TestMethod1_mult()
{
var calculator = new Calculator();
var result = calculator.Calculate("* 10 -20");
var expected = -200;
Assert.AreEqual(expected, result);
}
[Test]
public void TestMethod1_div()
{
var calculator = new Calculator();
var result = calculator.Calculate("/ 6 2");
var expected = 3;
Assert.AreEqual(expected, result);
}
and created the following code something like this:
public class Calculator
{
public int Calculate(string expression)
{
var tokens = expression.Split(' ');
var symbol = tokens[0];
var num1 = int.Parse(tokens[1]);
var num2 = int.Parse(tokens[2]);
switch (symbol)
{
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
return num1 / num2;
default:
throw new NotImplementedException("Symbol has not been implemented");
}
}
}