简体   繁体   中英

Conditional statements and how to increment a variable

i have the following code:

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
            }
        }
    }

The key bit is at the bottom with the comments Deletion, insertion and substitution, i was wondering how i could add a variable incrementor onto it so each time a deletion error is detected the variable increased by one. I've tried:

{           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
}

But just having no luck

As Eric said: Split the statement into multiple ones.

    else
    {
        substitutions = d[i - 1, j - 1] + 1;
        insertions =  Math.Min(d[i, j - 1] + 1, substitutions);
        deletion = Math.Min(d[i - 1, j] + 1, insertions);
        d[i, j] = deletion;

        if (/* whatever */)
            counter++;
    }

I am pretty sure it will do the same thing as before, but I don't know what you want to count as all lines are always executed.

I agree with @Eric and @usr, but just in case you are bent on doing this in a single statement (I know that one-liner's mentality, I've been a victim of it myself!), you can do it like (disclaimer: I haven't tested it):

Math.Min(d[i, j - 1] + 1 + (++insertion - insertion)

++ with increment the value of insertion and return the new value. So it will be like x - x = 0, therefore not affecting the larger statement.

EDIT

Sorry guys. This solution will only work in a ternary operator, which performs a short-circuit, whereas OP's question uses a function call, so this will evalaute every time, thereby killing the purpose of the counter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM