-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpression.cs
More file actions
328 lines (305 loc) · 11.2 KB
/
Expression.cs
File metadata and controls
328 lines (305 loc) · 11.2 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using static LogicParser.Operator;
namespace LogicParser
{
class Expression
{
public readonly bool HasOperator;
public bool not;
public readonly Operator op;
public readonly Expression Left;
public readonly Expression Right;
public readonly string variable;
public readonly List<Dictionary<string, bool>> TTable;
public readonly List<Dictionary<string, bool>> GTable;
public readonly List<Dictionary<string, bool>> BTable;
public int[,] KarnaughMap;
public Expression(string v, bool n = false)
{
HasOperator = false;
variable = v;
not = n;
BTable = BasicTruthTable();
TTable = TruthTable(generic: false);
GTable = TruthTable(generic: true);
}
public Expression(Expression l, Operator o, Expression r, bool n = false)
{
Left = l;
op = o;
Right = r;
not = n;
HasOperator = true;
BTable = BasicTruthTable();
TTable = TruthTable(generic: false);
GTable = TruthTable(generic: true);
}
public bool Evaluate(Dictionary<string, bool> vars)
{
if (!HasOperator)
{
return vars[variable] ^ not;
}
return op.Run(Left, Right, vars)();
}
internal List<Dictionary<string, bool>> BasicTruthTable()
{
List<string> vars = string.Concat(ToString().Where(e => !"-~()v>^+/\\".Contains(e))).Split().Where(e => e != string.Empty).Distinct().ToList();
List<Dictionary<string, bool>> r = new List<Dictionary<string, bool>>();
for (int i = 0; i < (int)Math.Pow(2, vars.Count); i++)
{
Dictionary<string, bool> row = new Dictionary<string, bool>();
for (int j = 0; j < vars.Count; j++)
{
row.Add(vars[j], (i & (1 << j)) == 0);
}
r.Add(row);
}
return r;
}
public void PrintTable(List<Dictionary<string, bool>> table = null)
{
table ??= TruthTable();
StringBuilder output = new StringBuilder();
foreach (Dictionary<string, bool> row in table)
{
foreach (KeyValuePair<string, bool> variable in row)
{
var t = variable.Value ^ not ? "T" : "F";
output.Append($"{variable.Key}: {t} | ");
}
output.Append("\n");
}
Console.WriteLine(output);
}
public static Expression Invert(Expression e)
{
e.not ^= true;
return e;
}
public override string ToString()
{
if (!HasOperator)
{
return (not ? "~" : "") + variable;
}
bool lParen = Left.HasOperator;
bool rParen = Left.HasOperator;
return (not ? "~(" : "") + (lParen ? "(" : "") + Left.ToString() + (lParen ? ") " : " ") + op + (rParen ? " (" : " ") + Right.ToString() + (lParen ? ")" : "") + (not ? ")" : "");
}
internal List<Dictionary<string, bool>> TruthTable(bool generic = false, List<Dictionary<string, bool>> table = null)
{
if (table == null) table = BasicTruthTable();
if (!generic)
{
if (HasOperator)
{
table = Left.TruthTable(false, table);
table = Right.TruthTable(false, table);
}
}
foreach (var row in table)
{
row.TryAdd(generic ? "conclusion" : ToString(), Evaluate(row));
}
return table;
}
public static Expression Parse(string exp)
{
exp = exp.Replace(" ", "");
if (exp.Count(e => e == '(') != exp.Count(e => e == ')'))
{
throw new ArgumentException("Invalid Expression");
}
int pos = exp.IndexOf("(");
var first = exp.Split('>');
if (first.Length > 1)
{
return new Expression(Parse(first[0]), IMPLIES, Parse(first[1]));
}
if (pos != -1)
{
int depth = 0;
bool foundOne = false;
for (int i = 0; i < exp.Length; i++)
{
if (exp[i] == '(')
{
foundOne = true;
depth++;
}
if (exp[i] == ')')
{
depth--;
}
if (depth == 0 && foundOne)
{
if (i + 2 < exp.Length)
{
var left = exp[1..i];
var right = exp[(i + 2)..];
var op = new Operator(exp.Substring(i + 1, 1)[0]);
return new Expression(Parse(left), op, Parse(right));
}
else
{
if (exp.StartsWith("~"))
{
return Invert(Parse(exp[(exp.IndexOf("(") + 1)..i]));
}
return Parse(exp[(exp.IndexOf("(") + 1)..i]);
}
}
}
}
if (first.Length == 1)
{
if (TooManyOps(exp, new List<char>() { 'v', '^', '/', '\\', '+' }))
{
throw new ArgumentException("Ambiguous Expression");
}
var ands = exp.Split("^");
var ors = exp.Split("v");
var nors = exp.Split("\\");
var nands = exp.Split("/");
var xors = exp.Split("+");
if (ands.Length > 1)
{
return CreateChainSingleExpression(ands, AND);
}
else if (ors.Length > 1)
{
return CreateChainSingleExpression(ors, OR);
}
else if (nors.Length > 1)
{
return CreateChainSingleExpression(nors, NOR);
}
else if (nands.Length > 1)
{
return CreateChainSingleExpression(nands, NAND);
}
else if (xors.Length > 1)
{
return CreateChainSingleExpression(xors, XOR);
}
else
{
return (exp.StartsWith("~") ? new Expression(exp[1..], true) : new Expression(exp));
}
}
else
{
throw new Exception("literally how this is not possible (length of array < 1)");
}
}
public static Expression CreateChainSingleExpression(IEnumerable<string> ss, Operator op)
{
if (ss.Count() == 1)
{
if (ss.First()[0] == '~')
return new Expression(ss.First()[1..], true);
return new Expression(ss.First());
}
Expression l;
if (ss.First()[0] == '~')
l = new Expression(ss.First()[1..], true);
else
l = new Expression(ss.First());
return new Expression(l, op, CreateChainSingleExpression(ss.Skip(1), op));
}
public override bool Equals(object obj)
{
if (!(obj is Expression)) return false;
Expression other = obj as Expression;
if (!TableEquals(GTable, other.GTable)) return false;
return true;
}
public static bool RowEquals<K, V>(Dictionary<K, V> first, Dictionary<K, V> second)
{
return first.Count == second.Count && !first.Except(second).Any();
}
public static bool TableEquals<K, V>(List<Dictionary<K, V>> first, List<Dictionary<K, V>> second)
{
if (first.Count != second.Count) return false;
for (int i = 0; i < first.Count; i++)
{
if (!RowEquals(first[i], second[i])) return false;
}
return true;
}
public static bool TooManyOps(string s, List<char> ops)
{
bool hasOne = false;
foreach (char c in ops)
{
if (s.Split(c).Length > 1)
{
if (hasOne) return true;
hasOne = true;
}
}
return false;
}
public override int GetHashCode()
{
return HashCode.Combine(HasOperator, not, op, Left, Right, variable);
}
public static Expression RandomExpression(int length = 1)
{
var ops = new string[] { "^", "v", ">", "\\", "/", "+" };
var vars = new string[] { "p", "q", "r", "s", "t", "u" };
var ran = new Random();
if (length <= 1) return Parse(vars[ran.Next(vars.Length)] + " " + ops[ran.Next(ops.Length)] + " " + vars[ran.Next(vars.Length)]);
else return new Expression(Parse(vars[ran.Next(vars.Length)] + " " + ops[ran.Next(ops.Length)] + " " + vars[ran.Next(vars.Length)]), new Operator(ops[ran.Next(ops.Length)][0]), RandomExpression(--length));
}
public void Prove()
{
bool satisfiable = GTable.Any(e => e["conclusion"]);
Console.WriteLine(string.Format("{0} is {1}", this, satisfiable));
Console.WriteLine($"simplified: TODO");
}
public bool Equivalent(Expression other)
{
if (other == null) return false;
if (other == this) return true;
return GTable.Select((e, i) => e["conclusion"] == other.GTable[i]["conclusion"]).All(e => e);
}
public void Simplify()
{
int width = ((int)Math.Ceiling(TTable.Count / 2f));
int height = ((int)Math.Floor(TTable.Count / 2f));
KarnaughMap = new int[width, height];
var GSTable = GrayCodeTable();
}
public List<Dictionary<string, bool>> GrayCodeTable(List<Dictionary<string, bool>> table = null)
{
table ??= GTable;
var o = new List<Dictionary<string, bool>>();
var order = GrayCode(table.Count);
foreach (int i in order)
{
o.Add(table[i]);
}
return o;
}
public static int[] GrayCode(int amount)
{
int current = 1;
int[] l1 = new[] { 0, 1 };
int[] l2;
while (l1.Length < amount)
{
l2 = l1.Reverse().ToArray();
int[] temp = l2.Select(e => e + ((int)Math.Pow(2, current))).ToArray();
l1 = l1.Concat(temp).ToArray();
current++;
}
return l1.Take(amount).ToArray();
}
}
}