-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathARITH2.cs
81 lines (73 loc) · 2.66 KB
/
ARITH2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.Linq;
// https://www.spoj.com/problems/ARITH2/ #ad-hoc #parsing #strings
// Parses a math expression and computes the result as if it were streamed in, ignoring precedence.
public static class ARITH2
{
public static long Solve(string expression)
{
string[] spacelessSubexpressions = expression.Split(
default(char[]), StringSplitOptions.RemoveEmptyEntries);
string[] tokens = spacelessSubexpressions
.SelectMany(s => s.SplitAndKeep(new[] { '+', '-', '*', '/', '=' }))
.ToArray();
// No negative integers simplifies things a bit. The input must be a number followed by
// (an operator and a number) and so on, ending with the equals operator.
long result = long.Parse(tokens[0]);
for (int i = 1; i < tokens.Length - 2; ++i)
{
char @operator = tokens[i][0];
long value = long.Parse(tokens[++i]);
switch (@operator)
{
case '+': result += value; break;
case '-': result -= value; break;
case '*': result *= value; break;
case '/': result /= value; break;
}
}
return result;
}
}
public static class StringHelper
{
// The StringSplitOptions.RemoveEmptyEntries is implicit here.
public static IEnumerable<string> SplitAndKeep(this string s, char[] delimiters)
{
int nextSubstringStartIndex = 0;
while (nextSubstringStartIndex < s.Length)
{
int nextDelimiterIndex = s.IndexOfAny(delimiters, nextSubstringStartIndex);
if (nextDelimiterIndex == nextSubstringStartIndex)
{
yield return s[nextSubstringStartIndex].ToString();
++nextSubstringStartIndex;
}
else if (nextDelimiterIndex > nextSubstringStartIndex)
{
yield return s.Substring(nextSubstringStartIndex,
length: nextDelimiterIndex - nextSubstringStartIndex);
nextSubstringStartIndex = nextDelimiterIndex;
}
else // No next delimiter found; nextDelimiterIndex = -1.
{
yield return s.Substring(nextSubstringStartIndex);
nextSubstringStartIndex = s.Length;
}
}
}
}
public static class Program
{
private static void Main()
{
int remainingTestCases = int.Parse(Console.ReadLine());
while (remainingTestCases-- > 0)
{
Console.ReadLine();
Console.WriteLine(
ARITH2.Solve(Console.ReadLine()));
}
}
}