-
Notifications
You must be signed in to change notification settings - Fork 47
/
Program.cs
47 lines (41 loc) · 1.27 KB
/
Program.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
/*
Description: Compress a string, very straightforward implementation without any external libraries.
Prerequisites: .net 6.0
Run using: csc compress_pp_v1.cs
*/
using System;
static string Compress(string sourceSequence)
{
if (string.IsNullOrEmpty(sourceSequence))
{
throw new ArgumentException($"'{nameof(sourceSequence)}' cannot be null or empty.", nameof(sourceSequence));
}
var currentPosition = 1;
var currentCharacter = sourceSequence.Substring(0, 1);
var numberOfRepetitions = 1;
var compressed = String.Empty;
while (currentPosition < sourceSequence.Length)
{
if (sourceSequence.Substring(currentPosition, 1) == currentCharacter)
{
numberOfRepetitions++;
}
else
{
compressed += $"{numberOfRepetitions}{currentCharacter}";
numberOfRepetitions = 1;
currentCharacter = sourceSequence.Substring(currentPosition, 1);
}
currentPosition++;
}
compressed += $"{numberOfRepetitions}{currentCharacter}";
return compressed;
}
static void Assert(string expected, string actual)
{
if (expected != actual)
{
throw new Exception($"Excpected: {expected}, but it is {actual}.");
}
}
Assert("3A2B2A1C", Compress("AAABBAAC"));