-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
98 lines (80 loc) · 2.42 KB
/
Program.cs
File metadata and controls
98 lines (80 loc) · 2.42 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System.Text.RegularExpressions;
Regex RomanRgx = new(@"^(?=.)M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Dictionary<char, int> Map = new()
{
{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},
{'C', 100}, {'D', 500}, {'M', 1000}
};
while (true)
{
Console.WriteLine("Enter values separated by spaces:");
string? inputLine = Console.ReadLine();
if (string.IsNullOrWhiteSpace(inputLine))
{
Console.WriteLine("No input provided. Exiting...");
return;
}
inputLine = inputLine.Replace("\"", "").Replace(",", " ");
List<string> mixedInputs = inputLine.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();
var (validItems, rejected) = testfunc(mixedInputs);
Console.WriteLine("\nSorted values:");
Console.WriteLine(string.Join(" ", validItems));
Console.WriteLine("\nRejected values:");
Console.WriteLine(rejected.Any() ? string.Join(" ", rejected) : "None");
}
(List<string> sorted, List<string> rejected) testfunc(IEnumerable<string> inputs)
{
var validList = new List<(string original, int value, bool isRoman)>();
var rejectedList = new List<string>();
foreach (var input in inputs)
{
if (IsValidInt(input, out int intValue))
{
validList.Add((input, intValue, false));
}
else if (IsValidRm(input, out int romanValue))
{
validList.Add((input, romanValue, true));
}
else
{
rejectedList.Add(input);
}
}
var sorted = validList
.OrderBy(x => x.value)
.Select(x => x.isRoman ? $"{x.original}({x.value})" : x.original)
.ToList();
return (sorted, rejectedList);
}
bool IsValidInt(string input, out int value)
{
if (int.TryParse(input, out value))
{
if (value >= 1 && value <= 3999) return true;
}
return false;
}
bool IsValidRm(string input, out int value)
{
value = 0;
if (!RomanRgx.IsMatch(input)) return false;
value = RmToInt(input);
return value >= 1 && value <= 3999;
}
int RmToInt(string roman)
{
roman = roman.ToUpper();
int total = 0;
int prevValue = 0;
for (int i = roman.Length - 1; i >= 0; i--)
{
var current = Map[roman[i]];
if (current < prevValue)
total -= current;
else
total += current;
prevValue = current;
}
return total;
}