【发布时间】:2024-01-12 11:11:01
【问题描述】:
我有以下代码:
public static int Compute(string a, string b, bool ignoreCase)
{
// Allocate distance matrix
int[,] d = new int[a.Length + 1, b.Length + 1];
// Get character comparer
CharComparer isEqual = (ignoreCase) ?
(CharComparer)CharCompareIgnoreCase : CharCompare;
// Compute distance
for (int i = 0; i <= a.Length; i++)
d[i, 0] = i;
for (int j = 0; j <= b.Length; j++)
d[0, j] = j;
for (int i = 1; i <= a.Length; i++)
{
for (int j = 1; j <= b.Length; j++)
{
if (isEqual(a[i - 1], b[j - 1]))
{
// No change required
d[i, j] = d[i - 1, j - 1];
}
else
{
d[i, j] =
Math.Min(d[i - 1, j] + 1, // Deletion
insertions= Math.Min(d[i, j - 1] + 1, // Insertion
substitutions= d[i - 1, j - 1] + 1)); // Substitution
}
}
}
关键位在 cmets 删除、插入和替换的底部,我想知道如何在其上添加变量增量器,以便每次检测到删除错误时,变量都会增加一。我试过了:
{ d[i, j] =
deletion= Math.Min(d[i - 1, j] + 1, // Deletion
insertions= Math.Min(d[i, j - 1] + 1 + insertion ++, // Insertion
substitutions= d[i - 1, j - 1] + 1)); // Substitution
}
只是运气不好
【问题讨论】:
-
像这样混合计算和副作用是一种非常糟糕的编程习惯;它使代码很难阅读。如果要执行计算,请执行计算并然后递增计数器。
-
Eric 是对的:只需将这个怪物的单个语句重组为多个语句,您就可以轻松实现目标!如果它变得太复杂而您无法理解 - 请简化。
标签: c# increment conditional-statements