-
Notifications
You must be signed in to change notification settings - Fork 1
/
gram.cs
117 lines (117 loc) · 3.71 KB
/
gram.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
namespace System.Grams {
public partial class Gram : IComparable<Gram> {
public static int Compare(int a, int b) {
return a - b;
}
public static int Compare(float[] a, float[] b) {
if (a == null && b == null) {
return 0;
} else if (a != null && b == null) {
return +1;
} else if (a == null && b != null) {
return -1;
}
for (int i = 0; i < a.Length && i < b.Length; i++) {
if (a[i] > b[i]) {
return +1;
} else if (a[i] < b[i]) {
return -1;
}
}
if (a.Length > b.Length) {
return +1;
} else if (a.Length < b.Length) {
return -1;
}
return 0;
}
public static int Compare(string a, string b) {
if (a == null && b == null) {
return 0;
} else if (a != null && b == null) {
return +1;
} else if (a == null && b != null) {
return -1;
}
for (int i = 0; i < a.Length && i < b.Length; i++) {
if (a[i] > b[i]) {
return +1;
} else if (a[i] < b[i]) {
return -1;
}
}
if (a.Length > b.Length) {
return +1;
} else if (a.Length < b.Length) {
return -1;
}
return 0;
}
public static int Score(Gram a, Gram b) {
if (a == null && b == null) {
return 0;
} else if (a != null && b == null) {
return +1;
} else if (a == null && b != null) {
return -1;
}
int c = -Gram.Compare(a.Vector, b.Vector);
if (c == 0) {
c = Gram.Compare(a.Key, b.Key);
}
return c;
}
public Gram(string key) {
if (key == null || key.Length == 0) {
throw new ArgumentNullException();
}
Key = key;
}
public Gram(string key, float[] vector) {
if (key == null || key.Length == 0) {
throw new ArgumentNullException();
}
Key = key;
Vector = vector;
}
public Gram(string key, int hash, Gram prev) {
if (key == null || key.Length == 0) {
throw new ArgumentNullException();
}
Key = key;
HashCode = hash;
Prev = prev;
}
int IComparable<Gram>.CompareTo(Gram other) {
return Compare(Key, other.Key);
}
public readonly Gram Prev;
public readonly int HashCode = -1;
public override int GetHashCode() {
return HashCode;
}
public readonly string Key;
public override string ToString() {
return Key;
}
public string ToString(string format) {
System.Text.StringBuilder fmt = new Text.StringBuilder();
fmt.Append("[");
if (Vector != null) {
for (int j = 0; j < Vector.Length; j++) {
if (j > 0) fmt.Append(" ");
fmt.Append(Vector[j].ToString(format));
}
}
fmt.Append("]");
return fmt.ToString();
}
public float Norm;
public float[] Vector;
public void Add(float[] vector, float c = 1.0f) {
for (int j = 0; j < Vector.Length; j++) {
Vector[j] += vector[j] * c;
}
}
}
}