Dewey Banks
Dewey Banks

Reputation: 323

Java: Find String with the highest value

I need to accept a string as input, split it into an array of individual words ( split on " ") and return the highest scoring word as a string. Each letter of a word scores points according to it's position in the alphabet: a = 1, b = 2, c = 3 etc. If two words score the same, I'll return the word that appears earliest in the original string. All letters will be lowercase and all inputs will be valid.

First, I decided that whether I score a string based on its total value as specified above, or simply use the ascii value, the result will be the same. So I choose to use the ascii value to make things simpler. I turn each word into a character array and the loop through to sum the total. Then I put the word and the total into a Hashmap. The next part I'm stuck on. How do I loop through the hashmap to find the largest value and then grab the associated word? This is a kate from a code kata site. I'm free to use whatever means I choose to solve it. So I'm not married to the hashmap idea.

Suggestions?

Here is my code thus far:

public static String high(String s) {
    // Your code here...


      HashMap<String, Integer> map = new HashMap<String, Integer>();
        String[] words = s.split(" ");

        // loop through all of the words, for each word get its value
        // and insert the word into map as key, value as that keys value
        for(int i = 0; i < words.length; i++) {
          char[] tempWordChars = words[i].toCharArray();
          int total = 0;
          for(int j = 0; j < tempWordChars.length; j++) {
            total = total + (int)tempWordChars[j];
          }

          map.put(tempWordChars.toString(), total);

        }

        return "";
      }

Upvotes: 0

Views: 5497

Answers (5)

rknife
rknife

Reputation: 300

If you do not care about the other strings, i.e they are of no value if a new high score word is found and only need the highest valued string, hashmap is an overkill. Keep traversing the input word by word and scoring each word, if you find a word with a higher score, update your output, otherwise continue till the end.

Also, if you need to keep all the strings with their score then: In order to get the maximum value word along with the word, you can use a Priority Queue (i.e a max heap) that heapify on the score of the word. Create a pair of word and score and insert it into priority queue.

Note: you will have to write a comparator for the queue.

Secondly, with this approach, you will get sorted output each time you extract the string.

Upvotes: 2

Shiv Krishna Jaiswal
Shiv Krishna Jaiswal

Reputation: 376

Using Java8,

import static java.util.Arrays.stream; import static java.util.Comparator.comparing; /* * Method to return highest scored word(which is defined * as sum of ASCII value of alphabets in word). * In case no word is present, Empty String is returned. */

public static String high(String s) {
    return stream(s.split("\\W+"))
            .max(comparing(str -> str.chars().sum()))
            .orElse("");
}

`

Upvotes: 2

Raju Sharma
Raju Sharma

Reputation: 2516

With java8

key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();      

System.out.println("Key : "+key+ " Maximum value : "+map.get(key));

Upvotes: 2

Sourav Gulati
Sourav Gulati

Reputation: 1359

try this

public static String high(String s) {

        String[] words = s.split(" ");
        int max = 0;
        String sToReturn = null;
        for (String word : words) {
            char[] tempWordChars = word.toCharArray();
            int total = 0;
            for (int j = 0; j < tempWordChars.length; j++) {
                total = total + (int) tempWordChars[j];
            }
            if (total > max) {
                sToReturn = word;
                max=total;
            }

        }

        return sToReturn;
    }

Upvotes: 2

Ryan Turnbull
Ryan Turnbull

Reputation: 3934

Something like this should work

Entry<String,Integer> maxTerm = null;

for(Entry<String,Integer> entry : hashMap.entrySet()) {

    if (maxTerm == null || entry.getValue() > maxTerm.getValue()) {
        maxTerm = entry;
    }
}

String wordFound = maxTerm.getKey();
int wordScore = maxTerm.getValue();

So you iterate through the hashmap, grabbing each entry, and if the entry has a value that is greater than any previous, you grab the Entry and you can gather the value and key from it, and use as you wish.

Upvotes: 1

Related Questions