задача Определить пуст ли язык в заданной грамматике..мне выдает кучу ошибок...вот алгоритм:Шаг 1. Начать коллекцию с единственного дерева, представленного только
корнем — узлом с меткой S.
Шаг 2. Добавить к коллекции любое дерево, которое может быть получено
из дерева, уже имеющегося в коллекции, посредством применения единственно-
го правила, если образующееся дерево не имеет ни одной ветви, длиннее m, и
если такого еще нет в коллекции. Поскольку число таких деревьев конечно, то
процесс в конце концов закончится.
Шаг 3.Теперь язык L(G) непуст, если в построенной коллекции есть хотя бы
одно дерево, представляющее вывод терминальной цепочки. Иначе язык L(G)
пуст.
C# |
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Symbol
{
private static List<Symbol> symbolTable;
public char symbol;
private Symbol(char s)
{
symbol = s;
}
public static Symbol getSymbol(char s)
{
if(symbolTable==NULL) symbolTable = new List<Symbol>();
if (s == 0)
throw new Exception("Symbol must not be 0!");
if(!char.IsLetter(s))
throw new Exception("Symbol must be letter!");
Object ob=symbolTable.Find(p => p.symbol == s);
if (ob!=NULL)
{
return((Symbol)ob);
}
else
{
Symbol symbol=new Symbol(s);
symbolTable.Add(symbol);
Console.WriteLine("ADDED NEW SYMBOL: " + s);
return symbol;
}
}
public bool isTerminal()
{
return(char.IsLower(symbol));
}
public static Boolean operator ==(Symbol s1, Symbol s2)
{
return (s1.symbol==s2.symbol);
}
public static Boolean operator !=(Symbol s1, Symbol s2)
{
return (s1.symbol != s2.symbol);
}
public static int countNonTerm()
{
if (symbolTable == NULL) return 0;
int i=0;
foreach (Symbol s in symbolTable)
{
if (!s.isTerminal())
i++;
}
return (i);
}
}
class Rule
{
private Symbol nonTerm;
private List<Symbol> chain;
public Rule(char nt, String chain)
{
nonTerm = Symbol.getSymbol(nt);
this.chain = new List<Symbol>();
for(int i=0;i<chain.Length;i++)
{
this.chain.Add(Symbol.getSymbol(chain[i]));
}
}
public void print()
{
Console.Write(nonTerm.symbol + " -> ");
foreach (Symbol sym in chain)
{
Console.Write(sym.symbol);
}
Console.Write("\n");
}
public Symbol getNonTerm()
{
return (nonTerm);
}
public List<Symbol> getChain()
{
return (chain);
}
}
//**************************************************************************//
class Chain
{
private static int chain_counter = 0;
private int id = 0;
private List<Symbol> tree;
public Chain()
{
tree = new List<Symbol>();
id = chain_counter++;
Console.WriteLine("NEW CHAIN: "+id);
}
public void addSymbol(Symbol s)
{
tree.Add(s);
Console.WriteLine("ADDED "+s.symbol+" TO CHAIN " + id);
}
public Chain getCopy()
{
Console.Write("FROM CHAIN: " + id+" ");
Chain newChain = new Chain();
foreach (Symbol s in tree)
{
newChain.addSymbol(s);
}
return newChain;
}
public bool allAreTerminal()
{
foreach (Symbol sym in tree)
{
if (!sym.isTerminal()) return (false);
}
return (true);
}
public void print()
{
Console.Write("CHAIN "+id+": ");
foreach (Symbol sym in tree)
{
Console.Write(sym.symbol);
}
Console.Write("\n");
}
}
//**************************************************************************//
class ForkNode
{
private int i,n;
public ForkNode(int i, int n)
{
this.i = i;
this.n = n;
}
public int getI()
{
return i;
}
public void incI()
{
i++;
}
public int getN()
{
return n;
}
}
class ForkTree
{
private ArrayList forks;
private int current_fork_index;
public ForkTree()
{
forks = new ArrayList();
current_fork_index = 0;
}
public void addForkNode(int i, int n)
{
forks.Add(new ForkNode(i, n));
}
public void reset()
{
current_fork_index = 0;
}
public void next()
{
current_fork_index++;
}
public bool isEmpty()
{
if(current_fork_index>forks.Count)
throw new Exception("Wrong fork pointer!");
return(current_fork_index==forks.Count);
}
public int getNumberOfRule()
{
return ((ForkNode)forks[current_fork_index]).getI();
}
public bool nextTree()
{
for (int i = forks.Count - 1; i >= 0; i--)
{
ForkNode fn = (ForkNode)forks[i];
fn.incI();
if (fn.getI() < fn.getN())
{
return(true);
}
else
{
forks.RemoveAt(i);
}
}
return (false);
}
public void print()
{
Console.Write("FORKTREE: ");
foreach (ForkNode fn in forks)
{
Console.Write("{"+fn.getI()+","+fn.getN()+"} ");
}
Console.Write("\n");
}
}
//**************************************************************************//
class Grammar
{
private List<Chain> outStrings;
private List<Rule> rules;
private int rules_num;
private string name;
private Symbol initialNonTerm;
private ForkTree forktree;
public Grammar(string name)
{
this.name = name;
rules_num = 0;
rules = new List<Rule>();
forktree = new ForkTree();
}
public void addRule(char nt, string chain)
{
rules.Add(new Rule(nt, chain));
rules_num++;
}
public void setInitialNonTerm(char nt)
{
initialNonTerm = Symbol.getSymbol(nt);
}
public void printRules()
{
Console.WriteLine("RULES:");
foreach (Rule rule in rules)
{
rule.print();
}
}
public bool check()
{
outStrings = new List<Chain>();
int depth = Symbol.countNonTerm();
Console.WriteLine("DEPTH: " + depth);
while (true)
{
Console.WriteLine("-----------------------");
Chain chain = new Chain();
outStrings.Add(chain);
forktree.reset();
passNonTerm(initialNonTerm, depth, chain);
Console.Write("RES ");
forktree.print();
bool result = forktree.nextTree();
Console.Write("INC ");
forktree.print();
if (!result) break;
}
Console.WriteLine("-----------------------");
bool check_result=false;
foreach (Chain c in outStrings)
{
c.print();
if (c.allAreTerminal())
{
check_result = true;
Console.WriteLine("CHECK PASSED: NON-TERMINAL STRING!");
}
}
return check_result;
}
private void passNonTerm(Symbol S, int level, Chain chain)
{
if ((level <= 0) || S.isTerminal())
{
chain.addSymbol(S);
return;
}
int num = 0;
int go=0;
foreach (Rule rule in rules)
if (rule.getNonTerm() == S)
num++;//counts number of variants
Console.WriteLine("NUM=" + num);
if(num>1)
{
if (forktree.isEmpty())
{
forktree.addForkNode(0,num);
go = 0;
}
else
{
go = forktree.getNumberOfRule();
}
forktree.next();
Console.WriteLine("GO=" + go);
}
//Tree tree_copy = tree.getCopy();
int counter = 0;
foreach (Rule rule in rules)
{
if (rule.getNonTerm() == S)
{
if (counter == go)
{
foreach (Symbol s in rule.getChain())
{
Console.WriteLine("PASS:" + s.symbol + "(" + (level - 1) + ")");
passNonTerm(s, level - 1, chain);
}
}
counter++;
}
}
}
}
//**************************************************************************//
class Program
{
static int main(string[] args)
{
try
{
Grammar grammar = new Grammar("G1");
grammar.addRule('S', "A");
grammar.addRule('A', "aBa");
grammar.addRule('A', "a");
grammar.addRule('B', "bBb");
grammar.addRule('B', "b");
//grammar.addRule('B', "c");
//grammar.addRule('A', "BB");
grammar.printRules();
grammar.setInitialNonTerm('S');
if(grammar.check())
Console.WriteLine("Language is not empty");
else
Console.WriteLine("Language is empty");
}
catch (Exception e)
{
Console.WriteLine("ERROR: " + e.Message);
}
Console.ReadKey();
}
}
} |
|