1

I'm stuck at some interesting task. I have 3 strings (hello, heavy & word). Need to calculate sum of each wold and print the biggest world and sum. For calculating - a = 1, z = 26. So hello = 50, heavy = 61 & word = 60. The biggest string is "heavy" and I need to print it like "heavy, 61". I found code who calculate chars from one string:

String[] words = {"hello", "heavy", "word"};

String str = "abc";
int sum = 0;

for (char ch : str.toCharArray()) {
    if (ch >= 'a' && ch <= 'z') {
        sum += 1 + ch - 'a';
    }
}
System.out.printf("%s %d%n", str, sum); //the result is abc, 6

The result from this code is: abc, 6

The question is, how to calculate all words and how to print the biggest one? I can write sum for each word and calculate it later, but in my task words are random from console. Scanning isn't problem.

Edit: All words are lowercase letters.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Would the value of `a` and `A` be the same? – Nicholas K Oct 21 '18 at 12:51
  • 1
    You are suppose to create a method that does it for a parameter. Then you call the method in a loop. – RealSkeptic Oct 21 '18 at 12:53
  • all words will be lowercase a-z – Николай Матев Oct 21 '18 at 13:01
  • Tip: Lowercase a-z are called lowercase [Basic Latin](http://www.unicode.org/charts/nameslist/index.html) letters. They have the properties of needing only one UTF-16 code unit to encode and of being consecutive in UTF-16. A Java [`char`](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html) is a UTF-16 code unit. (That makes your mapping simple `1 + ch - 'a'`.) UTF-16 is one of several character encodings for the [Unicode](http://www.unicode.org/charts/nameslist/index.html) character set. – Tom Blodget Oct 21 '18 at 15:31

3 Answers3

3

You can do something like this:

String[] words = { "hello", "heavy", "word" };

int biggestSum = 0;
String biggestWord = null;

for (String word : words) {
    int sum = 0;

    for (char ch : word.toLowerCase().toCharArray()) {
        if (ch >= 'a' && ch <= 'z') {
            sum += 1 + ch - 'a';
        }
    }

    if (sum > biggestSum) {
        biggestSum = sum;
        biggestWord = word;
    }

    System.out.printf("%s %d%n", word, sum);
}

System.out.printf("Biggest word: %s %d%n", biggestWord, biggestSum);

Here we loop through every word in words, and keep count of the sum of each word. After the sum has been calculated we can check if the sum of the current word is bigger than the biggest word found so far, and if that's the case we override biggestWord.

Mark
  • 5,089
  • 2
  • 20
  • 31
  • 1
    Thanks. This is very easy and short way for the task. I'll read more about "for (String word : words) {" – Николай Матев Oct 21 '18 at 13:22
  • 1
    `for (String word : words)` is a simpler, tighter concept for a loop. It's easier to write and read and translate to/from the problem domain. Verbalize it like this: "for each word in words". – Tom Blodget Oct 21 '18 at 15:36
1

For every word, calculate the word sum, and update a variable which holds the largest sum. For example:

int largestSum;
for (int i = 0; i < arrayOfWords.Length (); i++)
{
    // calculate the sum of the current word
    int currentWordSum = 0; 
    for (int j = 0; j < arrayOfWords[i].Length ();j++)
    {
        currentWordSum += (int)(arrayOfWords[j]);
        if (currentWordSum > largestSum)
        {
            largestSum = currentWordSum;
        }
    }
}
System.out.println (largestSum);
1

You can achieve it easily using a Map<String, Integer> where the key is String and the value is the weight.

public static void main(String[] args) {
    String[] words = { "hello", "heavy", "word" };
    Map<String, Integer> hmap = new HashMap<String, Integer>();

    for (int i = 0; i < words.length; i++) {
        hmap.put(words[i], 0);
    }

    hmap.forEach((k, v) -> {
        int tot = 0;
        for (char c : k.toCharArray()) {
            tot = tot + (c - 'a' + 1);
        }
        hmap.put(k, tot);
    });
 }

Now you can iterate over this map to find the heaviest string.

EDIT :

Without using map :

    String highString= "";
    int highest = 0;
    for (int i = 0; i < words.length; i++) {
        int tot = 0;
        for (char c : words[i].toCharArray()) {
            tot = tot + (c - 'a' + 1);
            if (highest < tot) {
                highest = tot;
                highString = words[i];
            }
        }
    }
    System.out.println(highString + "," + highest);
Nicholas K
  • 15,148
  • 7
  • 31
  • 57