private void BuilditemFamily() { // 初始化项目集族 List<HashSet> itemFamily = new List<HashSet>(); HashSet initialSet = new HashSet(); initialSet.Add("S'->.S"); itemFamily.Add(Closure(initialSet));

// 遍历项目集族
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 Closure(HashSet itemSet) { HashSet closure = new HashSet(); Stack stack = new Stack(itemSet);

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 Goto(HashSet itemSet, string symbol) { HashSet gotoSet = new 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 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录