Search code examples
javastringnumbersstring-comparison

Compare two strings with numbers as words


I have been given numbers as words:

{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};

Numbers are only up-to 10. And I my task is to compare given two input strings to each other.

It should basically work as you compare two numbers:

compare(1, 1) -> 0;
compare(1, 3) -> 1 < 3 as -1;
compare(5, 2) -> 5 > 2 as 1;

What would be the best suitable way to compare two strings like this?

Result would look something like this:

compare("one", "one") -> 0;
compare("one", "three") -> -1;
compare("five", "two") -> 1;
public int compare(String a, String b) {
    return 0;
}

Solution

  • You can use a map to code the Strings and their values. The benefit of this approach is that it has O(1) complexity as oppose to use of an array for instance.

    Map<String, Integer> map = Map.of("one", 1, "two", 2, ...);
    
    public int compare(String a, String b) {
          return Integer.compare(map.get(a),map.get(b));    
    }
    

    Full example:

    public class Example {
    
        private final static Map<String, Integer> STRING_VALUE =
                Map.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5,
                        "six", 6, "seven", 7, "eight", 8, "nine", 9, "ten", 10);
    
        public static int compare(String a, String b) {
            return Integer.compare(STRING_VALUE.get(a),STRING_VALUE.get(b));
        }
    
       public static void main(String[] args) {
           System.out.println(compare("one", "one"));
           System.out.println(compare("one", "three"));
           System.out.println(compare("five", "two"));
        }
    }
    

    Output:

    0
    -1
    1
    

    Another solution is to use an ENUM:

    Full Example:

    public class Example {
    
        enum Values {
            ONE,
            TWO,
            THREE,
            FOUR,
            FIVE,
            SIX,
            SEVEN,
            EIGHT,
            NINE,
            TEN;
        }
        public static int compare(String a, String b) {
            Values vA = Values.valueOf(a.toUpperCase());
            Values vB = Values.valueOf(b.toUpperCase());
            return Integer.compare(vA.compareTo(vB), 0);
        }
    
       public static void main(String[] args) {
           System.out.println(compare("one", "one"));
           System.out.println(compare("one", "three"));
           System.out.println(compare("five", "two"));
        }
    }
    

    Output:

    0
    -1
    1