根据下列代码请补充实现函数 BuilditemFamily;实现LR0文法构造项目集族的功能。输入文法如:S-aSbSc ;listView1中输出如:状态项目族信息 1 S-Sprivate Liststring productions = new Liststring; 存储文法产生式 private Liststring symbols = new Liststring;
private void BuilditemFamily()
{
// 初始化项目集族
List<HashSet
// 遍历项目集族
for (int i = 0; i < itemFamily.Count; i++)
{
HashSet<string> itemSet = itemFamily[i];
// 遍历文法符号
foreach (string symbol in symbols)
{
HashSet<string> gotoSet = Goto(itemSet, symbol);
// 如果goto集合不为空且不在项目集族中,则加入项目集族
if (gotoSet.Count > 0 && !itemFamily.Contains(gotoSet))
{
itemFamily.Add(gotoSet);
}
}
}
// 将项目集族转换为字符串形式
for (int i = 0; i < itemFamily.Count; i++)
{
HashSet<string> itemSet = itemFamily[i];
string itemSetStr = "";
foreach (string item in itemSet)
{
itemSetStr += item + "\n";
}
itemsets.Add(itemSetStr.Trim());
states.Add("I" + i);
}
}
// 计算闭包
private HashSet
while (stack.Count > 0)
{
string item = stack.Pop();
closure.Add(item);
string[] parts = item.Split(new char[] { '-', '>' }, StringSplitOptions.RemoveEmptyEntries);
int dotIndex = parts[1].IndexOf('.');
// 如果点号在最后,则不需要计算闭包
if (dotIndex == parts[1].Length - 1)
{
continue;
}
string nextSymbol = parts[1][dotIndex + 1].ToString();
// 如果nextSymbol是非终结符,则加入其产生式
if (symbols.Contains(nextSymbol))
{
foreach (string production in productions)
{
string[] productionParts = production.Split(new char[] { '-', '>' }, StringSplitOptions.RemoveEmptyEntries);
if (productionParts[0] == nextSymbol)
{
string newItem = nextSymbol + "->." + productionParts[1];
if (!closure.Contains(newItem))
{
stack.Push(newItem);
}
}
}
}
}
return closure;
}
// 计算Goto集合
private HashSet
foreach (string item in itemSet)
{
string[] parts = item.Split(new char[] { '-', '>' }, StringSplitOptions.RemoveEmptyEntries);
int dotIndex = parts[1].IndexOf('.');
// 如果点号不在最后且下一个符号是symbol,则移动点号
if (dotIndex < parts[1].Length - 1 && parts[1][dotIndex + 1].ToString() == symbol)
{
string newItem = parts[0] + "->" + parts[1].Substring(0, dotIndex + 1) + symbol + "." + parts[1].Substring(dotIndex + 2);
gotoSet.Add(newItem);
}
}
return Closure(gotoSet);
原文地址: https://www.cveoy.top/t/topic/heTe 著作权归作者所有。请勿转载和采集!