我必须在Delphi7中实现一个决策矩阵。
功能是
CalcNewStatus(操作代码:字符串;报告类型:字符串;当前状态:字符串):字符串;
ActionCode的值可以是“A”和“N”
reporttype可以有值“i”和“f”
currentStatus的值可以是“p”、“i”、“f”。
例如,在C语言中,我会使用字典在Delphi 7中,我如何做到这一点?

最佳答案

将输入字符规范化为基于零的序数值,事情就变得简单多了。从几个类型声明开始:

type
  TActionCode = (acA, acN);
  TReportType = (rtI, rtF);
  TStatus = (sP, sI, sF);

然后,可以使用这些类型和所有可能的状态值来定义数组。用每个点的状态值替换sX
const
  NextStatus: array[TActionCode, TReportType, TStatus] of TStatus = (
    {acA} (// sP, sI, sF
      {rtI} ( sX, sX, sX),
      {rtF} ( sX, sX, sX)
          ),
    {acN} (
      {rtI} ( sX, sX, sX),
      {rtF} ( sX, sX, sX)
          )
  );

那么你的功能就是:
function CalcNewStatus(const actionCode, reportType, currentStatus: string): string;
var
  ac: TActionCode;
  rt: TReportType;
  s: TStatus;
const
  StateChars: array[TState] of Char = ('P', 'I', 'F');
begin
  Assert(actionCode <> ''); Assert(reportType <> ''); Assert(currentStatus <> '');
  Assert(actionCode[1] in ['A', 'N']);
  Assert(reportType[1] in ['I', 'F']);
  Assert(currentStatus[1] in ['P', 'I', 'F']);
  if actionCode[1] = 'A' then ac := acA else ac := acN;
  if reportType[1] = 'I' then rt := rtI else rt := rtF;
  if currentStatus[1] = 'P' then s := sP
  else if currentStatus[1] = 'I' then s := sI
  else s := sF;

  Result := StateChars[NextStatus[ac, rt, s]];
end;

如您所见,这段代码的大部分用于在字符串和枚举类型之间进行转换如果可以,在这种情况下请避免使用字符串在程序中尽早切换到枚举类型,只有在绝对需要时才转换回字符串或字符。字符串可以有任意长度,这是您不必处理的,而且字符串的值也可以超出您定义的范围Enums不能,除非你做些奇怪的事此外,编译器不会让您意外地在需要treporttype的地方使用tstate值,这将帮助您避免混淆i和f。

关于algorithm - 如何在Delphi中实现决策矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9579392/

10-09 07:25