Search code examples
processinglevenshtein-distanceedit-distance

Distance edit array output


I am doing an edit distance with the user input. I am storing my values in array. then the edit distance will compare the user input with my array of strings. I am doing a loop that if the edit distance is more than 2 it will display invalid else valid.

The only problem I've got is that although the program is working out fine, the output is the result of all the '28' strings that I have in my array. I would like to display only invalid or valid once.

Test is my array of strings and user is - String user - the user input.

void testingLD()
{
  for (int i=0; i<test.length; i++)
  {
      if(getLevenshteinDistance(test[i],user) > 2)
      {
        println ("Invalid re-input");
      }
      else 
      {
        println ("Valid");
      }
  }
}

Solution

  • You have your print line functions inside your loop so they get printed once per iteration.

    Try this.

    void testingLD()
    {
      boolean isValid = true; // assume true, check each and update
    
      // begin loop
      for (int i=0; i<test.length; i++)
      {
          if(getLevenshteinDistance(test[i],user) > 2)
          {
            isValid = false;
            break; // don't need to test the rest of the loop if we already found a false
          }
      }
      // end loop
    
      if(isValid){
        println("Valid");
      }else{
        println("Invalid re-input");
      }
    }
    

    Similarly you could count the number of valid int validCount = 0; validCount++ and then display stats about how many were valid, the percentage etc. Or keep an array of the invalid strings and display those as the ones that fail etc!

    Wrap up: When you want to check an entire collection or array for some condition and output one answer make sure to have your output outside of the loop!