Determine the Highest Scoring Word in Java


The challenge

Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.

The solution in Java code

Option 1:

import java.util.*;

public class HSW {
    public static String high(String s) {
        return Arrays.stream(s.split(" "))
                .max(Comparator.comparingInt(
                        a -> a.chars().map(i -> i - 96).sum()
                )).get(); 
    }
}

Option 2:

import java.util.Arrays;
import java.util.Comparator;

class HSW {
    static String high(String s) {
        return Arrays.stream(s.split( " " ))
                .sorted( Comparator.comparingInt( HSW::cws )
                        .reversed()).findFirst().get();
    }
    private static int cws(String y) {
        return y.chars().map( i->i-(int)'a'+1 ).sum();
    }
}

Option 3:

public class HSW {

    public static String high(String stringOfWords) {
        String highscoreWord = "";
        int maxTotal = 0;

        for (String word : stringOfWords.split(" ")) {
            int totalOfWord = 0;
            for (char c : word.toCharArray()) {
                totalOfWord += c - 96; // the int value of "a" is 97
            }
            if (totalOfWord > maxTotal) {
                maxTotal = totalOfWord;
                highscoreWord = word;
            }
        }
        return highscoreWord;
    }

}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.*;
import java.util.stream.*;

public class SolutionTest {

    private static String _high(String s) {
      return Stream.of(s.split(" "))
        .sorted(Comparator.comparing((String a) -> a.chars().map(b -> b - 96).sum()).reversed())
        .findFirst().get();
    }
    
    @Test
    public void sampleTests() {
        assertEquals("taxi", HSW.high("man i need a taxi up to ubud"));
        assertEquals("volcano", HSW.high("what time are we climbing up to the volcano"));
        assertEquals("semynak", HSW.high("take me to semynak"));
    }
    
    @Test
    public void randomTests() {
      String chars = "      abcdefghijklmnopqrstuvwxyz";
      Random random = new Random();
      
      for (int i = 0; i < 100; ++i) {
        String test = IntStream.range(10, random.nextInt(201))
          .mapToObj(x -> Character.toString(chars.charAt(random.nextInt(chars.length()))))
          .collect(Collectors.joining()).trim().replaceAll("\\s+", " ");
        
        String expected = _high(test);
        String actual = HSW.high(test);
        
        assertEquals(expected, actual);
      }
    }
}