ci: compile the manual
[nit.git] / lib / crapto / english_utils.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2016 Philippe Pépos Petitclerc <ppeposp@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # English language utilities for cryptographic purposes.
18 module english_utils
19
20 redef class Sys
21 # English letter frequency map
22 var english_freqs: HashMap[Char, Float] is lazy do
23 var freqs = new HashMap[Char, Float]
24
25 freqs['a'] = 0.0651738
26 freqs['b'] = 0.0124248
27 freqs['c'] = 0.0217339
28 freqs['d'] = 0.0349835
29 freqs['e'] = 0.1041442
30 freqs['f'] = 0.0197881
31 freqs['g'] = 0.0158610
32 freqs['h'] = 0.0492888
33 freqs['i'] = 0.0558094
34 freqs['j'] = 0.0009033
35 freqs['k'] = 0.0050529
36 freqs['l'] = 0.0331490
37 freqs['m'] = 0.0202124
38 freqs['n'] = 0.0564513
39 freqs['o'] = 0.0596302
40 freqs['p'] = 0.0137645
41 freqs['q'] = 0.0008606
42 freqs['r'] = 0.0497563
43 freqs['s'] = 0.0515760
44 freqs['t'] = 0.0729357
45 freqs['u'] = 0.0225134
46 freqs['v'] = 0.0082903
47 freqs['w'] = 0.0171272
48 freqs['x'] = 0.0013692
49 freqs['y'] = 0.0145984
50 freqs['z'] = 0.0007836
51 freqs[' '] = 0.1918182
52
53 return freqs
54 end
55 end
56
57 redef class Text
58
59 # Score `self` according to english's letter frequency.
60 # This function is useful mainly for cryptography but could happen to be helpful
61 # elsewhere.
62 #
63 # assert "aaaa".english_scoring > "bbbb".english_scoring
64 fun english_scoring: Float do
65
66 var freqs = english_freqs
67 var score = 0.0
68
69 for c in self do
70 c = c.to_lower
71 var points = freqs.get_or_null(c)
72 if points != null then
73 score += points
74 end
75 end
76
77 return score
78
79 end
80 end