Thursday, October 8, 2015

Matching

Problem:

TopCoder Problem Statement - Matching
Single Round Match 176 Round 1 - Division I, Level One
Single Round Match 176 Round 1 - Division II, Level Two

Overview:

Find the card which completes the pattern. For each group of characteristics, the matching card must either share the trait with the other two cards, or all three cards must have a different value.

Java Source:
     1 public class Matching {
     2
     3  private static final String[][] TRAITS = {
     4    {"CIRCLE", "SQUIGGLE", "DIAMOND"},
     5    {"BLUE", "RED", "GREEN"},
     6    {"SOLID", "STRIPED", "EMPTY"},
     7    {"ONE", "TWO", "THREE"}
     8  };
     9
    10  public String[] findMatch(String[] first, String[] second) {
    11
    12   String[] result = new String[4];
    13
    14   for (int i = 0; i < TRAITS.length; i++)  {
    15    result[i] = getMatch(first[i], second[i], TRAITS[i]);
    16   }
    17
    18   return result;
    19
    20  }
    21
    22  private static String getMatch(String s1, String s2, String[] traits)  {
    23
    24   /*
    25   * If the two strings are equal, then return that string.
    26   */
    27   if (s1.equals(s2)) return s1;
    28
    29   /*
    30   * Otherwise, return the string that is not s1 or s2
    31   */
    32   for (int i = 0; i < traits.length; i++)  {
    33    if (!traits[i].equals(s1) && !traits[i].equals(s2))
    34     return traits[i];
    35   }
    36
    37   return null;
    38
    39  }
    40 }
Notes:

This is one of those problems where reading the description makes you think it's going to be much more difficult than the problem actually is. All we need to do is for each of the four traits (shape, color, fill pattern, and count) give the value of the string if the first and second card have the same value. Or, if the first and second cards have different values, then we give the third (or odd man out) value.

The for loop in the findMatch() method just walks through each of the four traits, and calls getMatch() to insert the correct value into the result array.

getMatch() compares the two strings, and if they're equal returns that value. Otherwise, it looks through the values given in traits for a string that does not match s1 and does not match s2. Note that we should never reach the return null statement on line 37, but it needs to be there to satisfy the compiler.

Nothing difficult here. Getting through the description actually took longer than writing the code.

No comments:

Post a Comment