-
Notifications
You must be signed in to change notification settings - Fork 3
/
AbsoluteCharacterFrequencies.cs
55 lines (42 loc) · 1.64 KB
/
AbsoluteCharacterFrequencies.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
using System.Collections;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Linq;
namespace Science.Cryptography.Ciphers.Analysis;
public readonly record struct AbsoluteCharacterFrequencies(IReadOnlyDictionary<char, int> Frequencies) : IReadOnlyDictionary<char, int>
{
/// <summary>
/// Gets the occurrences of a given <paramref name="character"/>.
/// </summary>
/// <param name="character"></param>
/// <returns></returns>
public readonly int this[char character]
{
get
{
Frequencies.TryGetValue(character, out int frequency);
return frequency;
}
}
public readonly RelativeCharacterFrequencies ToRelativeFrequencies()
{
var sum = Frequencies.Sum(f => f.Value);
return new(
Frequencies.ToFrozenDictionary(
kv => kv.Key,
kv => kv.Value / (double)sum
)
);
}
public readonly IReadOnlyDictionary<char, int> ToDictionary() => Frequencies;
#region IReadOnlyDictionary<char, int>
IEnumerable<char> IReadOnlyDictionary<char, int>.Keys => Frequencies.Keys;
IEnumerable<int> IReadOnlyDictionary<char, int>.Values => Frequencies.Values;
int IReadOnlyCollection<KeyValuePair<char, int>>.Count => Frequencies.Count;
int IReadOnlyDictionary<char, int>.this[char key] => this[key];
bool IReadOnlyDictionary<char, int>.ContainsKey(char key) => Frequencies.ContainsKey(key);
bool IReadOnlyDictionary<char, int>.TryGetValue(char key, out int value) => Frequencies.TryGetValue(key, out value);
IEnumerator<KeyValuePair<char, int>> IEnumerable<KeyValuePair<char, int>>.GetEnumerator() => Frequencies.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => Frequencies.GetEnumerator();
#endregion
}