1
\$\begingroup\$

Let's say I have the following array of Strings:

String[] rows = new String[]{
  "",
  "A",
  "B C C",
  "",
  "B D E",
  "E F G H"
};

As well as the following pairs:

String[] pairs = new String[]{
  "H F",
  "A B",
  "A E",
  "G B"
};

How can I calculate the smallest difference between the two pairs in the array? So the output would be the following for the pairs:

"H F" -> 0   // (both in the 6th item of the array)
"A B" -> 1   // (2nd and 3rd items of the array)
"A E" -> 3   // (2nd and 5th items of the array; 2nd and 6th would be larger)
"G B" -> 1   // (5th and 6th items of the array; 3rd and 6th would be larger)

I have been able to accomplish this with the following code, but I have the feeling this can be done better/shorter instead of the three nested for-loops..

int[] calculateMinDistanceOfPairs(String[] rows, String[] pairs){
  // Result int-array:
  int rowLength = rows.length,
              c = 0,
              d = rowLength,
              i,j;
  int[] result = new int[pairs.length];
  // Loop (1) over the pairs:
  for(String pair : pairs){
    // Inner loop (2) over the rows
    for(i=1, d=rowLength; i<rowLength; i++){
      // If the current row contains the first item of the pair:
      if(rows[i].contains(pair.split(" ")[0])){
        // Inner loop (3) over the rows again
        for(j=1; j<rowLength; j++){
          // If the current row contains the second item of the pair:
          if(rows[j].contains(pair.split(" ")[1])){
            // Change `d` to:
            d =
                j-i > 0 ?   // If j-i is larger than 0:
                 j-i < d ?  //  If j-i is smaller than `d`:
                  j-i       //   `d` is now j-i
                 :          //  Else:
                  d         //   `d` remains the same
               :            // Else (i-j is larger than or equal to 0):
                 i-j < d?   //  If i-j is smaller than `d`:
                  i-j       //   `d` is now i-j
                 :          //  Else:
                  d;        //   `d` remains the same
          }
        } // End of inner loop (3)
      }
    } // End of inner loop (2)
    // Add `d` to the result-array:
    result[c++] = d;
  } // End of loop (1)
  return result;
}

Try it in this online compiler.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I'm not entirely sure how this code runs. Could you please add in the method declaration and the initialisation of the variables d and o? \$\endgroup\$
    – Imus
    Jun 27 '17 at 7:03
  • \$\begingroup\$ @Imus d and o were a mistake.. I made this answer for a code-golf challenge (hence the short variable names), and then re-written it manually for review here. But it's fixed now, and I've also added a TIO-link at the bottom. \$\endgroup\$ Jun 27 '17 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.