在 C# 代码中表示 DFA 转换表的最简单方法是什么?



这是我到目前为止要做的,所以在 DFA 中,你有状态,并且你有这些状态之间的过渡,从state Astate B你消耗symbol ex: 'a'。现在我正在尝试编写一个需要current state (int) and a transition symbol (char) and returns the next state (int)DFA transition function,现在要做到这一点,您必须有权访问过渡表,现在表示该过渡表的最佳方式是什么,这是我到目前为止得到的:

Dictionary<int, Dictionary<char, int>> transitionMap = new Dictionary<int, Dictionary<char, int>>();

那是我的过渡图,它是第一个int key is current statenested dictionary consists of symbol consumed and the other int is the next state that I have to return的字典,我遇到的问题是字典不能有重复的键(在这种情况下状态(和DFA可以有多个转换相同的状态。例如,如果我尝试这样做:

Dictionary<char, int> dict = new Dictionary<char, int>();
dict.Add('a', 1);  // 'a' here is the symbol consumed to go to state 1 from state 0
transitionMap.Add(0, dict); // 0 is the current state

现在当我添加这个时,它可以工作,但是当我尝试为状态 0 添加另一个过渡时,它没有,因为字典不能有重复的键,那么这里该怎么办?

是的,所以我在理解字典时遇到了问题,我现在明白了:

if (transitionMap.ContainsKey(state))
{
Dictionary<char, int> res = new Dictionary<char, int>();   
transitionMap.TryGetValue(state, out res);
res.Add(symbol, nextState);
transitionMap[state] = res;
}

我只需要检查状态是否存在,然后拿起字典,向其添加另一个过渡并添加到transitionMap。

最新更新