Created
March 1, 2018 19:47
-
-
Save am0d/ac6af9918a52bcabf505632a872daba6 to your computer and use it in GitHub Desktop.
Interview calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Entry point name must be "Solution" | |
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
public static class Solution | |
{ | |
private static void Main() | |
{ | |
Console.WriteLine("*** Test Results ***"); | |
Tests.TestAll(); | |
} | |
} | |
public class Calculator { | |
private string _input; | |
private IEnumerable<string> _tokens; | |
public Calculator(string input) { | |
_input = input; | |
_tokens = Utils.SplitStringToTokens(_input); | |
} | |
public int GetResult() { | |
string firstNumber = _tokens.ElementAt(0); | |
//string op = _tokens.ElementAt(1); | |
string secondNumber = _tokens.ElementAt(2); | |
var first = Utils.NumberFromString(firstNumber); | |
var second = Utils.NumberFromString(secondNumber); | |
return first + second; | |
} | |
} | |
public static class Utils { | |
public static int NumberFromString(string input) { | |
return int.Parse(input); | |
} | |
public static IEnumerable<string> SplitStringToTokens(string input) { | |
string nextToken = string.Empty; | |
foreach (var currentChar in input) { | |
if (Char.IsNumber(currentChar)) { | |
nextToken += currentChar; | |
continue; | |
} | |
if (!string.IsNullOrEmpty(nextToken)) { | |
yield return nextToken; | |
nextToken = string.Empty; | |
} | |
yield return currentChar.ToString(); | |
} | |
yield return nextToken; | |
} | |
} | |
public static class Tests { | |
public static void TestAll() { | |
Test1(); | |
} | |
public static void Test1() { | |
var input = "1+2"; | |
const int EXPECTED = 3; | |
AssertEqual(EXPECTED, new Calculator(input).GetResult()); | |
} | |
private static void AssertEqual(object expected, object actual) { | |
if (!expected.Equals(actual)) { | |
Console.WriteLine("X Expected {0}, actual result: {1}", expected, actual); | |
} else { | |
Console.WriteLine(" {0} == {1}", expected, actual); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment